<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  <!-- 谷歌收录 -->
  <meta name="google-site-verification" content="-5hl8eC4wfapGZhZouwMVUcKG0iaynijVRJbqVlzXm4" />
  
  
  <title>力扣简洁优雅的python解法 | 鴻塵</title>
  <meta name="description" content="摘要：Python语言特点之一就是优雅简洁，为方便学习数据结构，搬运自Github【项目地址】上汇总LeetCode最短最优雅的解法的项目。">
<meta property="og:type" content="article">
<meta property="og:title" content="力扣简洁优雅的python解法">
<meta property="og:url" content="https://hwame.top/20200604/shortest-leetcode-python-solutions.html">
<meta property="og:site_name" content="鴻塵">
<meta property="og:description" content="摘要：Python语言特点之一就是优雅简洁，为方便学习数据结构，搬运自Github【项目地址】上汇总LeetCode最短最优雅的解法的项目。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://hwame.top/20200604/思维导图.jpg">
<meta property="og:image" content="https://hwame.top/20200604/tree.png">
<meta property="article:published_time" content="2020-06-04T13:32:55.000Z">
<meta property="article:modified_time" content="2020-06-05T03:42:18.000Z">
<meta property="article:author" content="鴻塵">
<meta property="article:tag" content="数据结构与算法">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://hwame.top/20200604/思维导图.jpg">
  <!-- Canonical links -->
  <link rel="canonical" href="https://hwame.top/20200604/shortest-leetcode-python-solutions.html">
  
    <link rel="alternate" href="true" title="鴻塵" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/css/style.css">

  
  
  
    <link href="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css" rel="stylesheet">
  
  
<meta name="generator" content="Hexo 5.4.2"></head>


<script src="https://cdn.jsdelivr.net/gh/bobcn/hexo_resize_image.js@master/hexo_resize_image.js"></script>
<body class="main-center theme-purple" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="https://hwame.top" target="_blank">
          <img class="img-circle img-rotate" src="https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">鴻塵</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">Pythoner, Data Analyst</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> 湖北-武汉</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav menu-highlight">
        
        
        <li class="menu-item menu-item-home">
          <a href="/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">首页</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">归档</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/categories">
            
            <i class="icon icon-folder-open"></i>
            
            <span class="menu-title">分类</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">标签</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-repository">
          <a href="/repository">
            
            <i class="icon icon-project"></i>
            
            <span class="menu-title">资源</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-gallery">
          <a href="/gallery">
            
            <i class="icon icon-delicious"></i>
            
            <span class="menu-title">相册</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-links">
          <a href="/links">
            
            <i class="icon icon-friendship"></i>
            
            <span class="menu-title">友链</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-about">
          <a href="/about">
            
            <i class="icon icon-cup-fill"></i>
            
            <span class="menu-title">关于</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/hwame" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="https://weibo.com/hwamei" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="https://www.zhihu.com/people/hwame" target="_blank" title="Zhihu" data-toggle=tooltip data-placement=top><i class="icon icon-zhihu"></i></a></li>
        
        <li><a href="https://segmentfault.com/u/hwame" target="_blank" title="Segmentfault" data-toggle=tooltip data-placement=top><i class="icon icon-segmentfault"></i></a></li>
        
        <li><a href="https://gitee.com/hwame" target="_blank" title="Gitee" data-toggle=tooltip data-placement=top><i class="icon icon-gitee"></i></a></li>
        
        <li><a href="/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-stackexchange"></i>公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>欢迎来到鴻塵的博客!<br>鴻塵的<u><a target="_blank" rel="noopener" href="https://weibo.com/hwamei" style="color:#E541E5;">微博</a></u>主页，鴻塵的<u><a target="_blank" rel="noopener" href="https://github.com/hwame" style="color:#E541E5;">Github</a></u>主页，如果我可以忘记的<u><a target="_blank" rel="noopener" href="https://www.zhihu.com/people/hwame" style="color:#E541E5;">知乎</a></u>主页。</p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-tags"></i>标签云</h3>
    <div class="widget-body tagcloud">
      <a href="/tags/CentOS/" style="font-size: 13px; color: #fff">CentOS</a> <a href="/tags/Go/" style="font-size: 13.2px; color: #fff">Go</a> <a href="/tags/Hexo/" style="font-size: 13.8px; color: #fff">Hexo</a> <a href="/tags/Linux/" style="font-size: 14px; color: #fff">Linux</a> <a href="/tags/Linux%E9%83%A8%E7%BD%B2/" style="font-size: 13px; color: #fff">Linux部署</a> <a href="/tags/MongoDB/" style="font-size: 13.4px; color: #fff">MongoDB</a> <a href="/tags/Spark/" style="font-size: 13px; color: #fff">Spark</a> <a href="/tags/matplotlib/" style="font-size: 13.2px; color: #fff">matplotlib</a> <a href="/tags/miscellanea/" style="font-size: 13.6px; color: #fff">miscellanea</a> <a href="/tags/python/" style="font-size: 14px; color: #fff">python</a> <a href="/tags/shell/" style="font-size: 13.6px; color: #fff">shell</a> <a href="/tags/%E5%A4%A7%E6%95%B0%E6%8D%AE/" style="font-size: 13px; color: #fff">大数据</a> <a href="/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" style="font-size: 13px; color: #fff">数据结构与算法</a> <a href="/tags/%E7%88%AC%E8%99%AB/" style="font-size: 13px; color: #fff">爬虫</a>
    </div>
  </div>

<script type="text/javascript">
    var everytag=document.getElementsByClassName("widget-body tagcloud")[0].children;
    for (var i = everytag.length - 1; i >= 0; i--) {
    	var r=Math.floor(Math.random()*255);
        var g=Math.floor(Math.random()*255);
        var b=Math.floor(Math.random()*255);
        everytag[i].style.background = "rgb("+r+","+g+","+b+")";
    }
</script>
    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-folder-open"></i>分类</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Go/">Go</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Hexo/">Hexo</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Linux/">Linux</a><span class="category-list-count">8</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/MongoDB/">MongoDB</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/miscellanea/">miscellanea</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/python/">python</a><span class="category-list-count">7</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/">数据结构与算法</a><span class="category-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-archives-fill"></i>归档</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2022/">2022</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/">2021</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/">2020</a><span class="archive-list-count">17</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-shu-fill"></i>最新文章</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled ">
        
          <li>
            
            <div class="item-thumb">
              <a href="/20220327/channel-and-goroutine-in-go.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/icon-golang.jpeg)" alt="Go语言中的通道" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Go/">Go</a>
              </p>
              <p class="item-title">
                <a href="/20220327/channel-and-goroutine-in-go.html" class="title">Go语言中的通道</a>
              </p>
              <p class="item-date">
                <time datetime="2022-03-27T11:06:16.000Z" itemprop="datePublished">2022-03-27</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220323/when-to-use-pointer-in-go.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/icon-golang.jpeg)" alt="Go语言什么时候使用指针" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Go/">Go</a>
              </p>
              <p class="item-title">
                <a href="/20220323/when-to-use-pointer-in-go.html" class="title">Go语言什么时候使用指针</a>
              </p>
              <p class="item-date">
                <time datetime="2022-03-23T12:49:57.000Z" itemprop="datePublished">2022-03-23</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220228/awesome-images-in-markdown.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg)" alt="Markdown中图片的高级用法" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/miscellanea/">miscellanea</a>
              </p>
              <p class="item-title">
                <a href="/20220228/awesome-images-in-markdown.html" class="title">Markdown中图片的高级用法</a>
              </p>
              <p class="item-date">
                <time datetime="2022-02-28T15:27:50.000Z" itemprop="datePublished">2022-02-28</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220116/shell-regular-expression.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/linux-icon.png)" alt="Shell正则表达式" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Linux/">Linux</a>
              </p>
              <p class="item-title">
                <a href="/20220116/shell-regular-expression.html" class="title">Shell正则表达式</a>
              </p>
              <p class="item-date">
                <time datetime="2022-01-16T14:13:05.000Z" itemprop="datePublished">2022-01-16</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20211009/install-linux-on-android-phone.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg)" alt="如何在安卓手机上安装Linux发行版" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/miscellanea/">miscellanea</a>
              </p>
              <p class="item-title">
                <a href="/20211009/install-linux-on-android-phone.html" class="title">如何在安卓手机上安装Linux发行版</a>
              </p>
              <p class="item-date">
                <time datetime="2021-10-09T15:16:37.000Z" itemprop="datePublished">2021-10-09</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <nav id="toc" class="article-toc">
      <h3 class="toc-title">文章目录</h3>
      <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E9%87%8C%E7%A8%8B%E7%A2%91"><span class="toc-number">2.</span> <span class="toc-text">里程碑</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8E%A8%E8%8D%90"><span class="toc-number">2.1.</span> <span class="toc-text">推荐</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E9%A2%98%E5%BA%93%E8%A7%A3%E6%9E%90"><span class="toc-number">3.</span> <span class="toc-text">题库解析</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-Two-Sum-4%E8%A1%8C"><span class="toc-number">3.1.</span> <span class="toc-text">1. Two Sum 4行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-Add-Two-Numbers-5%E8%A1%8C"><span class="toc-number">3.2.</span> <span class="toc-text">2. Add Two Numbers 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-Longest-Substring-Without-Repeating-Characters-3%E8%A1%8C"><span class="toc-number">3.3.</span> <span class="toc-text">3. Longest Substring Without Repeating Characters 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-Median-of-Two-Sorted-Arrays-5%E8%A1%8C"><span class="toc-number">3.4.</span> <span class="toc-text">4. Median of Two Sorted Arrays 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-Longest-Palindromic-Substring-5%E8%A1%8C"><span class="toc-number">3.5.</span> <span class="toc-text">5. Longest Palindromic Substring 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7-Reverse-Integer-2%E8%A1%8C"><span class="toc-number">3.6.</span> <span class="toc-text">7. Reverse Integer 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8-String-to-Integer-atoi-1%E8%A1%8C"><span class="toc-number">3.7.</span> <span class="toc-text">8. String to Integer (atoi) 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9-Palindrome-Number-1%E8%A1%8C"><span class="toc-number">3.8.</span> <span class="toc-text">9. Palindrome Number 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#11-Container-With-Most-Water-3%E8%A1%8C"><span class="toc-number">3.9.</span> <span class="toc-text">11. Container With Most Water 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#13-Roman-to-Integer-2%E8%A1%8C"><span class="toc-number">3.10.</span> <span class="toc-text">13. Roman to Integer 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#14-Longest-Common-Prefix-2%E8%A1%8C"><span class="toc-number">3.11.</span> <span class="toc-text">14. Longest Common Prefix 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#15-3Sum-5%E8%A1%8C"><span class="toc-number">3.12.</span> <span class="toc-text">15. 3Sum 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#16-3Sum-Closest-7%E8%A1%8C"><span class="toc-number">3.13.</span> <span class="toc-text">16. 3Sum Closest 7行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#17-Letter-Combinations-of-a-Phone-Number-3%E8%A1%8C"><span class="toc-number">3.14.</span> <span class="toc-text">17. Letter Combinations of a Phone Number 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#18-4Sum-5%E8%A1%8C"><span class="toc-number">3.15.</span> <span class="toc-text">18. 4Sum 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#19-Remove-Nth-Node-From-End-of-List-5%E8%A1%8C"><span class="toc-number">3.16.</span> <span class="toc-text">19. Remove Nth Node From End of List 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#20-Valid-Parentheses-2%E8%A1%8C"><span class="toc-number">3.17.</span> <span class="toc-text">20. Valid Parentheses 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#21-Merge-Two-Sorted-Lists-4%E8%A1%8C"><span class="toc-number">3.18.</span> <span class="toc-text">21. Merge Two Sorted Lists 4行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#23-Merge-k-Sorted-Lists-4%E8%A1%8C"><span class="toc-number">3.19.</span> <span class="toc-text">23. Merge k Sorted Lists 4行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#24-Swap-Nodes-in-Pairs-3%E8%A1%8C"><span class="toc-number">3.20.</span> <span class="toc-text">24. Swap Nodes in Pairs 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#26-Remove-Duplicates-from-Sorted-Array-3%E8%A1%8C"><span class="toc-number">3.21.</span> <span class="toc-text">26. Remove Duplicates from Sorted Array 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#28-Implement-strStr-1%E8%A1%8C"><span class="toc-number">3.22.</span> <span class="toc-text">28. Implement strStr() 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#29-Divide-Two-Integers-5%E8%A1%8C"><span class="toc-number">3.23.</span> <span class="toc-text">29. Divide Two Integers 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#33-Search-in-Rotated-Sorted-Array-3%E8%A1%8C"><span class="toc-number">3.24.</span> <span class="toc-text">33. Search in Rotated Sorted Array 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#34-%E5%9C%A8%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84%E4%B8%AD%E6%9F%A5%E6%89%BE%E5%85%83%E7%B4%A0%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E5%92%8C%E6%9C%80%E5%90%8E%E4%B8%80%E4%B8%AA%E4%BD%8D%E7%BD%AE"><span class="toc-number">3.25.</span> <span class="toc-text">34. 在排序数组中查找元素的第一个和最后一个位置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#35-Search-Insert-Position-1%E8%A1%8C"><span class="toc-number">3.26.</span> <span class="toc-text">35. Search Insert Position 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#36-Valid-Sudoku-4%E8%A1%8C"><span class="toc-number">3.27.</span> <span class="toc-text">36. Valid Sudoku 4行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#38-Count-and-Say-1%E8%A1%8C"><span class="toc-number">3.28.</span> <span class="toc-text">38. Count and Say 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#43-Multiply-Strings-5%E8%A1%8C"><span class="toc-number">3.29.</span> <span class="toc-text">43. Multiply Strings 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#46-Permutations-1%E8%A1%8C"><span class="toc-number">3.30.</span> <span class="toc-text">46. Permutations 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#49-Group-Anagrams-1%E8%A1%8C"><span class="toc-number">3.31.</span> <span class="toc-text">49. Group Anagrams 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#50-Pow-x-n-2%E8%A1%8C"><span class="toc-number">3.32.</span> <span class="toc-text">50. Pow(x, n) 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#53-Maximum-Subarray-2%E8%A1%8C"><span class="toc-number">3.33.</span> <span class="toc-text">53. Maximum Subarray 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#54-Spiral-Matrix-1%E8%A1%8C"><span class="toc-number">3.34.</span> <span class="toc-text">54. Spiral Matrix 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#58-Length-of-Last-Word-1%E8%A1%8C"><span class="toc-number">3.35.</span> <span class="toc-text">58. Length of Last Word 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#59-Spiral-Matrix-II-3%E8%A1%8C"><span class="toc-number">3.36.</span> <span class="toc-text">59. Spiral Matrix II 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#61-Rotate-List-4%E8%A1%8C"><span class="toc-number">3.37.</span> <span class="toc-text">61. Rotate List 4行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#62-Unique-Paths-1%E8%A1%8C"><span class="toc-number">3.38.</span> <span class="toc-text">62. Unique Paths 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#66-Plus-One-1%E8%A1%8C"><span class="toc-number">3.39.</span> <span class="toc-text">66. Plus One 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#67-Add-Binary-1%E8%A1%8C"><span class="toc-number">3.40.</span> <span class="toc-text">67. Add Binary 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#69-Sqrt-x-1%E8%A1%8C"><span class="toc-number">3.41.</span> <span class="toc-text">69. Sqrt(x) 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#70-Climbing-Stairs-2%E8%A1%8C"><span class="toc-number">3.42.</span> <span class="toc-text">70. Climbing Stairs 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#71-Simplify-Path-4%E8%A1%8C"><span class="toc-number">3.43.</span> <span class="toc-text">71. Simplify Path 4行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#73-%E7%9F%A9%E9%98%B5%E7%BD%AE%E9%9B%B6-5%E8%A1%8C"><span class="toc-number">3.44.</span> <span class="toc-text">73. 矩阵置零  5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#74-%E6%90%9C%E7%B4%A2%E4%BA%8C%E7%BB%B4%E7%9F%A9%E9%98%B5-4%E8%A1%8C"><span class="toc-number">3.45.</span> <span class="toc-text">74. 搜索二维矩阵 4行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#78-Subsets-2%E8%A1%8C"><span class="toc-number">3.46.</span> <span class="toc-text">78. Subsets 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#80-%E5%88%A0%E9%99%A4%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84%E4%B8%AD%E7%9A%84%E9%87%8D%E5%A4%8D%E9%A1%B9-II-4%E8%A1%8C"><span class="toc-number">3.47.</span> <span class="toc-text">80. 删除排序数组中的重复项 II 4行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#81-%E6%90%9C%E7%B4%A2%E6%97%8B%E8%BD%AC%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84-II-1%E8%A1%8C"><span class="toc-number">3.48.</span> <span class="toc-text">81. 搜索旋转排序数组 II 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#83-Remove-Duplicates-from-Sorted-List-3%E8%A1%8C"><span class="toc-number">3.49.</span> <span class="toc-text">83. Remove Duplicates from Sorted List 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#88-Merge-Sorted-Array-1%E8%A1%8C"><span class="toc-number">3.50.</span> <span class="toc-text">88. Merge Sorted Array 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#89-Gray-Code-1%E8%A1%8C"><span class="toc-number">3.51.</span> <span class="toc-text">89. Gray Code 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#91-Decode-Ways-4%E8%A1%8C"><span class="toc-number">3.52.</span> <span class="toc-text">91. Decode Ways 4行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#94-Binary-Tree-Inorder-Traversal-2%E8%A1%8C"><span class="toc-number">3.53.</span> <span class="toc-text">94. Binary Tree Inorder Traversal 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#98-Validate-Binary-Search-Tree-3%E8%A1%8C"><span class="toc-number">3.54.</span> <span class="toc-text">98. Validate Binary Search Tree 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#101-Symmetric-Tree-5%E8%A1%8C"><span class="toc-number">3.55.</span> <span class="toc-text">101. Symmetric Tree 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#104-Maximum-Depth-of-Binary-Tree-1%E8%A1%8C"><span class="toc-number">3.56.</span> <span class="toc-text">104. Maximum Depth of Binary Tree 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#110-%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91-3%E8%A1%8C"><span class="toc-number">3.57.</span> <span class="toc-text">110. 平衡二叉树 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#112-Path-Sum-3%E8%A1%8C"><span class="toc-number">3.58.</span> <span class="toc-text">112. Path Sum 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#118-Pascal%E2%80%99s-Triangle-1%E8%A1%8C"><span class="toc-number">3.59.</span> <span class="toc-text">118. Pascal’s Triangle 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#121-Best-Time-to-Buy-and-Sell-Stock-2%E8%A1%8C"><span class="toc-number">3.60.</span> <span class="toc-text">121. Best Time to Buy and Sell Stock 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#122-Best-Time-to-Buy-and-Sell-Stock-II-2%E8%A1%8C"><span class="toc-number">3.61.</span> <span class="toc-text">122. Best Time to Buy and Sell Stock II 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#124-Binary-Tree-Maximum-Path-Sum-4%E8%A1%8C"><span class="toc-number">3.62.</span> <span class="toc-text">124. Binary Tree Maximum Path Sum 4行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#133-Clone-Graph"><span class="toc-number">3.63.</span> <span class="toc-text">133. Clone Graph</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#136-Single-Number-2%E8%A1%8C"><span class="toc-number">3.64.</span> <span class="toc-text">136. Single Number 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#138-Copy-List-with-Random-Pointer-1%E8%A1%8C"><span class="toc-number">3.65.</span> <span class="toc-text">138. Copy List with Random Pointer 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#139-Word-Break-8%E8%A1%8C"><span class="toc-number">3.66.</span> <span class="toc-text">139. Word Break 8行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#141-Linked-List-Cycle-2%E8%A1%8C"><span class="toc-number">3.67.</span> <span class="toc-text">141. Linked List Cycle 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#142-Linked-List-Cycle-II-5%E8%A1%8C"><span class="toc-number">3.68.</span> <span class="toc-text">142. Linked List Cycle II 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#146-LRU-Cache-7%E8%A1%8C"><span class="toc-number">3.69.</span> <span class="toc-text">146. LRU Cache 7行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#148-Sort-List-10%E8%A1%8C"><span class="toc-number">3.70.</span> <span class="toc-text">148. Sort List 10行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#150-Evaluate-Reverse-Polish-Notation-5%E8%A1%8C"><span class="toc-number">3.71.</span> <span class="toc-text">150. Evaluate Reverse Polish Notation 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#155-Min-Stack-%E6%AF%8F%E4%B8%AA1%E8%A1%8C"><span class="toc-number">3.72.</span> <span class="toc-text">155. Min Stack 每个1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#160-Intersection-of-Two-Linked-Lists-3%E8%A1%8C"><span class="toc-number">3.73.</span> <span class="toc-text">160. Intersection of Two Linked Lists 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#162-Find-Peak-Element-2%E8%A1%8C"><span class="toc-number">3.74.</span> <span class="toc-text">162. Find Peak Element 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#165-Compare-Version-Numbers-4%E8%A1%8C"><span class="toc-number">3.75.</span> <span class="toc-text">165. Compare Version Numbers 4行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#169-Majority-Element-1%E8%A1%8C"><span class="toc-number">3.76.</span> <span class="toc-text">169. Majority Element 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#171-Excel-Sheet-Column-Number-1%E8%A1%8C"><span class="toc-number">3.77.</span> <span class="toc-text">171. Excel Sheet Column Number 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#173-Binary-Search-Tree-Iterator-6%E8%A1%8C"><span class="toc-number">3.78.</span> <span class="toc-text">173. Binary Search Tree Iterator 6行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#189-Rotate-Array-1%E8%A1%8C"><span class="toc-number">3.79.</span> <span class="toc-text">189. Rotate Array 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#190-Reverse-Bits-1%E8%A1%8C"><span class="toc-number">3.80.</span> <span class="toc-text">190. Reverse Bits 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#191-Number-of-1-Bits-1%E8%A1%8C"><span class="toc-number">3.81.</span> <span class="toc-text">191. Number of 1 Bits 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#198-House-Robber-2%E8%A1%8C"><span class="toc-number">3.82.</span> <span class="toc-text">198. House Robber 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#200-Number-of-Islands-7%E8%A1%8C"><span class="toc-number">3.83.</span> <span class="toc-text">200. Number of Islands 7行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#202-Happy-Number-1%E8%A1%8C"><span class="toc-number">3.84.</span> <span class="toc-text">202. Happy Number 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#203-Remove-Linked-List-Elements-2%E8%A1%8C"><span class="toc-number">3.85.</span> <span class="toc-text">203. Remove Linked List Elements 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#205-Isomorphic-Strings-1%E8%A1%8C"><span class="toc-number">3.86.</span> <span class="toc-text">205. Isomorphic Strings 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#206-Reverse-Linked-List-2%E8%A1%8C"><span class="toc-number">3.87.</span> <span class="toc-text">206. Reverse Linked List 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#215-Kth-Largest-Element-in-an-Array-1%E8%A1%8C"><span class="toc-number">3.88.</span> <span class="toc-text">215. Kth Largest Element in an Array 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#217-Contains-Duplicate-1%E8%A1%8C"><span class="toc-number">3.89.</span> <span class="toc-text">217. Contains Duplicate 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#219-Contains-Duplicate-II-4%E8%A1%8C"><span class="toc-number">3.90.</span> <span class="toc-text">219. Contains Duplicate II 4行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#225-Implement-Stack-using-Queues-6%E8%A1%8C"><span class="toc-number">3.91.</span> <span class="toc-text">225. Implement Stack using Queues 6行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#230-Kth-Smallest-Element-in-a-BST-3%E8%A1%8C"><span class="toc-number">3.92.</span> <span class="toc-text">230. Kth Smallest Element in a BST 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#231-2%E7%9A%84%E5%B9%82-1%E8%A1%8C"><span class="toc-number">3.93.</span> <span class="toc-text">231. 2的幂 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#232-Implement-Queue-using-Stacks-13%E8%A1%8C"><span class="toc-number">3.94.</span> <span class="toc-text">232. Implement Queue using Stacks 13行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#234-Palindrome-Linked-List-3%E8%A1%8C"><span class="toc-number">3.95.</span> <span class="toc-text">234. Palindrome Linked List 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree-2%E8%A1%8C"><span class="toc-number">3.96.</span> <span class="toc-text">235. Lowest Common Ancestor of a Binary Search Tree 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#236-Lowest-Common-Ancestor-of-a-Binary-Tree-2%E8%A1%8C"><span class="toc-number">3.97.</span> <span class="toc-text">236. Lowest Common Ancestor of a Binary Tree 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#237-Delete-Node-in-a-Linked-List-1%E8%A1%8C"><span class="toc-number">3.98.</span> <span class="toc-text">237. Delete Node in a Linked List 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#238-Product-of-Array-Except-Self-5%E8%A1%8C"><span class="toc-number">3.99.</span> <span class="toc-text">238. Product of Array Except Self 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#240-Search-a-2D-Matrix-II-1%E8%A1%8C"><span class="toc-number">3.100.</span> <span class="toc-text">240. Search a 2D Matrix II 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#258-Add-Digits-1%E8%A1%8C"><span class="toc-number">3.101.</span> <span class="toc-text">258. Add Digits 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#268-Missing-Number-1%E8%A1%8C"><span class="toc-number">3.102.</span> <span class="toc-text">268. Missing Number 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#278-First-Bad-Version-2%E8%A1%8C"><span class="toc-number">3.103.</span> <span class="toc-text">278. First Bad Version 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#279-Perfect-Squares-4%E8%A1%8C"><span class="toc-number">3.104.</span> <span class="toc-text">279. Perfect Squares 4行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#283-Move-Zeroes-1%E8%A1%8C"><span class="toc-number">3.105.</span> <span class="toc-text">283. Move Zeroes 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#287-Find-the-Duplicate-Number-2%E8%A1%8C"><span class="toc-number">3.106.</span> <span class="toc-text">287. Find the Duplicate Number 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#292-Nim-Game-1%E8%A1%8C"><span class="toc-number">3.107.</span> <span class="toc-text">292. Nim Game 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#326-Power-of-Three-1%E8%A1%8C"><span class="toc-number">3.108.</span> <span class="toc-text">326. Power of Three 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#328-Odd-Even-Linked-List-6%E8%A1%8C"><span class="toc-number">3.109.</span> <span class="toc-text">328. Odd Even Linked List 6行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#342-Power-of-Four-1%E8%A1%8C"><span class="toc-number">3.110.</span> <span class="toc-text">342. Power of Four 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#344-Reverse-String-1%E8%A1%8C"><span class="toc-number">3.111.</span> <span class="toc-text">344. Reverse String 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#345-Reverse-Vowels-of-a-String-2%E8%A1%8C"><span class="toc-number">3.112.</span> <span class="toc-text">345. Reverse Vowels of a String 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#347-Top-K-Frequent-Elements-1%E8%A1%8C"><span class="toc-number">3.113.</span> <span class="toc-text">347. Top K Frequent Elements 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#349-Intersection-of-Two-Arrays-1%E8%A1%8C"><span class="toc-number">3.114.</span> <span class="toc-text">349. Intersection of Two Arrays 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#350-Intersection-of-Two-Arrays-II-1%E8%A1%8C"><span class="toc-number">3.115.</span> <span class="toc-text">350. Intersection of Two Arrays II 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#367-Valid-Perfect-Square-4%E8%A1%8C"><span class="toc-number">3.116.</span> <span class="toc-text">367. Valid Perfect Square 4行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#387-First-Unique-Character-in-a-String-2%E8%A1%8C"><span class="toc-number">3.117.</span> <span class="toc-text">387. First Unique Character in a String 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#389-Find-the-Difference-1%E8%A1%8C"><span class="toc-number">3.118.</span> <span class="toc-text">389. Find the Difference 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#394-Decode-String-14%E8%A1%8C"><span class="toc-number">3.119.</span> <span class="toc-text">394. Decode String 14行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#412-Fizz-Buzz-1%E8%A1%8C"><span class="toc-number">3.120.</span> <span class="toc-text">412. Fizz Buzz 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#414-Third-Maximum-Number-3%E8%A1%8C"><span class="toc-number">3.121.</span> <span class="toc-text">414. Third Maximum Number 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#430-Flatten-a-Multilevel-Doubly-Linked-List-5%E8%A1%8C"><span class="toc-number">3.122.</span> <span class="toc-text">430. Flatten a Multilevel Doubly Linked List 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#448-Find-All-Numbers-Disappeared-in-an-Array-1%E8%A1%8C"><span class="toc-number">3.123.</span> <span class="toc-text">448. Find All Numbers Disappeared in an Array 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#454-4Sum-II-2%E8%A1%8C"><span class="toc-number">3.124.</span> <span class="toc-text">454. 4Sum II 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#461-Hamming-Distance-1%E8%A1%8C"><span class="toc-number">3.125.</span> <span class="toc-text">461. Hamming Distance 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#485-Max-Consecutive-Ones-1%E8%A1%8C"><span class="toc-number">3.126.</span> <span class="toc-text">485. Max Consecutive Ones 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#494-Target-Sum-5%E8%A1%8C"><span class="toc-number">3.127.</span> <span class="toc-text">494. Target Sum 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#495-Teemo-Attacking"><span class="toc-number">3.128.</span> <span class="toc-text">495. Teemo Attacking</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#498-Diagonal-Traverse-5%E8%A1%8C"><span class="toc-number">3.129.</span> <span class="toc-text">498. Diagonal Traverse 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#507-Perfect-Number"><span class="toc-number">3.130.</span> <span class="toc-text">507. Perfect Number</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#557-Reverse-Words-in-a-String-III-1%E8%A1%8C"><span class="toc-number">3.131.</span> <span class="toc-text">557. Reverse Words in a String III 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#561-Array-Partition-I-1%E8%A1%8C"><span class="toc-number">3.132.</span> <span class="toc-text">561. Array Partition I 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#575-Distribute-Candies-1%E8%A1%8C"><span class="toc-number">3.133.</span> <span class="toc-text">575. Distribute Candies 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#581-Shortest-Unsorted-Continuous-Subarray-2%E8%A1%8C"><span class="toc-number">3.134.</span> <span class="toc-text">581. Shortest Unsorted Continuous Subarray 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#589-N-ary-Tree-Preorder-Traversal-1%E8%A1%8C"><span class="toc-number">3.135.</span> <span class="toc-text">589. N-ary Tree Preorder Traversal 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#599-Minimum-Index-Sum-of-Two-Lists-2%E8%A1%8C"><span class="toc-number">3.136.</span> <span class="toc-text">599. Minimum Index Sum of Two Lists 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#652-Find-Duplicate-Subtrees-8%E8%A1%8C"><span class="toc-number">3.137.</span> <span class="toc-text">652. Find Duplicate Subtrees 8行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#658-Find-K-Closest-Elements-2%E8%A1%8C"><span class="toc-number">3.138.</span> <span class="toc-text">658. Find K Closest Elements 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#700-Search-in-a-Binary-Search-Tree-1%E8%A1%8C"><span class="toc-number">3.139.</span> <span class="toc-text">700. Search in a Binary Search Tree 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#703-Kth-Largest-Element-in-a-Stream-3%E8%A1%8C"><span class="toc-number">3.140.</span> <span class="toc-text">703. Kth Largest Element in a Stream 3行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#724-Find-Pivot-Index-4%E8%A1%8C"><span class="toc-number">3.141.</span> <span class="toc-text">724. Find Pivot Index 4行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#733-Flood-Fill-6%E8%A1%8C"><span class="toc-number">3.142.</span> <span class="toc-text">733. Flood Fill 6行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#739-Daily-Temperatures-5%E8%A1%8C"><span class="toc-number">3.143.</span> <span class="toc-text">739. Daily Temperatures 5行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#744-Find-Smallest-Letter-Greater-Than-Target"><span class="toc-number">3.144.</span> <span class="toc-text">744. Find Smallest Letter Greater Than Target</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#747-Largest-Number-At-Least-Twice-of-Others-2%E8%A1%8C"><span class="toc-number">3.145.</span> <span class="toc-text">747. Largest Number At Least Twice of Others 2行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#752-Open-the-Lock-11%E8%A1%8C"><span class="toc-number">3.146.</span> <span class="toc-text">752. Open the Lock 11行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#771-Jewels-and-Stones-1%E8%A1%8C"><span class="toc-number">3.147.</span> <span class="toc-text">771. Jewels and Stones 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#867-Transpose-Matrix-1%E8%A1%8C"><span class="toc-number">3.148.</span> <span class="toc-text">867. Transpose Matrix 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#938-Range-Sum-of-BST-1%E8%A1%8C"><span class="toc-number">3.149.</span> <span class="toc-text">938. Range Sum of BST 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#953-Verifying-an-Alien-Dictionary-1%E8%A1%8C"><span class="toc-number">3.150.</span> <span class="toc-text">953. Verifying an Alien Dictionary 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#973-K-Closest-Points-to-Origin-1%E8%A1%8C"><span class="toc-number">3.151.</span> <span class="toc-text">973. K Closest Points to Origin 1行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1290-Convert-Binary-Number-in-a-Linked-List-to-Integer"><span class="toc-number">3.152.</span> <span class="toc-text">1290. Convert Binary Number in a Linked List to Integer</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%93%E9%A2%98%E6%8E%A2%E7%B4%A2"><span class="toc-number">4.</span> <span class="toc-text">专题探索</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%EF%BC%8C%E8%AF%B4%E9%9A%BE%E4%B9%9F%E4%B8%8D%E9%9A%BE"><span class="toc-number">4.1.</span> <span class="toc-text">数据结构，说难也不难</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%F0%9F%8C%A0-%E9%98%9F%E5%88%97-amp-%E6%A0%88"><span class="toc-number">4.1.1.</span> <span class="toc-text">🌠 队列 &amp; 栈</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#622-%E8%AE%BE%E8%AE%A1%E5%BE%AA%E7%8E%AF%E9%98%9F%E5%88%97"><span class="toc-number">4.1.1.1.</span> <span class="toc-text">622. 设计循环队列</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#200-%E5%B2%9B%E5%B1%BF%E7%9A%84%E4%B8%AA%E6%95%B0"><span class="toc-number">4.1.1.2.</span> <span class="toc-text">200. 岛屿的个数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#752-%E6%89%93%E5%BC%80%E8%BD%AC%E7%9B%98%E9%94%81"><span class="toc-number">4.1.1.3.</span> <span class="toc-text">752. 打开转盘锁</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#279-%E5%AE%8C%E5%85%A8%E5%B9%B3%E6%96%B9%E6%95%B0"><span class="toc-number">4.1.1.4.</span> <span class="toc-text">279. 完全平方数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#155-%E6%9C%80%E5%B0%8F%E6%A0%88"><span class="toc-number">4.1.1.5.</span> <span class="toc-text">155. 最小栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#20-%E6%9C%89%E6%95%88%E7%9A%84%E6%8B%AC%E5%8F%B7"><span class="toc-number">4.1.1.6.</span> <span class="toc-text">20. 有效的括号</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#739-%E6%AF%8F%E6%97%A5%E6%B8%A9%E5%BA%A6"><span class="toc-number">4.1.1.7.</span> <span class="toc-text">739. 每日温度</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#150-%E9%80%86%E6%B3%A2%E5%85%B0%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%B1%82%E5%80%BC"><span class="toc-number">4.1.1.8.</span> <span class="toc-text">150. 逆波兰表达式求值</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#200-%E5%B2%9B%E5%B1%BF%E7%9A%84%E4%B8%AA%E6%95%B0-1"><span class="toc-number">4.1.1.9.</span> <span class="toc-text">200. 岛屿的个数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#133-%E5%85%8B%E9%9A%86%E5%9B%BE"><span class="toc-number">4.1.1.10.</span> <span class="toc-text">133. 克隆图</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#494-%E7%9B%AE%E6%A0%87%E5%92%8C"><span class="toc-number">4.1.1.11.</span> <span class="toc-text">494. 目标和</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#94-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E4%B8%AD%E5%BA%8F%E9%81%8D%E5%8E%86"><span class="toc-number">4.1.1.12.</span> <span class="toc-text">94. 二叉树的中序遍历</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#232-%E7%94%A8%E6%A0%88%E5%AE%9E%E7%8E%B0%E9%98%9F%E5%88%97"><span class="toc-number">4.1.1.13.</span> <span class="toc-text">232. 用栈实现队列</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#225-%E7%94%A8%E9%98%9F%E5%88%97%E5%AE%9E%E7%8E%B0%E6%A0%88"><span class="toc-number">4.1.1.14.</span> <span class="toc-text">225. 用队列实现栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#394-%E5%AD%97%E7%AC%A6%E4%B8%B2%E8%A7%A3%E7%A0%81"><span class="toc-number">4.1.1.15.</span> <span class="toc-text">394. 字符串解码</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#733-%E5%9B%BE%E5%83%8F%E6%B8%B2%E6%9F%93"><span class="toc-number">4.1.1.16.</span> <span class="toc-text">733. 图像渲染</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#542-01-%E7%9F%A9%E9%98%B5"><span class="toc-number">4.1.1.17.</span> <span class="toc-text">542. 01 矩阵</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#841-%E9%92%A5%E5%8C%99%E5%92%8C%E6%88%BF%E9%97%B4"><span class="toc-number">4.1.1.18.</span> <span class="toc-text">841. 钥匙和房间</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%F0%9F%8C%A0-%E6%95%B0%E7%BB%84%E5%92%8C%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-number">4.1.2.</span> <span class="toc-text">🌠 数组和字符串</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#724-%E5%AF%BB%E6%89%BE%E6%95%B0%E7%BB%84%E7%9A%84%E4%B8%AD%E5%BF%83%E7%B4%A2%E5%BC%95"><span class="toc-number">4.1.2.1.</span> <span class="toc-text">724. 寻找数组的中心索引</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#747-%E8%87%B3%E5%B0%91%E6%98%AF%E5%85%B6%E4%BB%96%E6%95%B0%E5%AD%97%E4%B8%A4%E5%80%8D%E7%9A%84%E6%9C%80%E5%A4%A7%E6%95%B0"><span class="toc-number">4.1.2.2.</span> <span class="toc-text">747. 至少是其他数字两倍的最大数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#66-%E5%8A%A0%E4%B8%80"><span class="toc-number">4.1.2.3.</span> <span class="toc-text">66. 加一</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#498-%E5%AF%B9%E8%A7%92%E7%BA%BF%E9%81%8D%E5%8E%86"><span class="toc-number">4.1.2.4.</span> <span class="toc-text">498. 对角线遍历</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#54-%E8%9E%BA%E6%97%8B%E7%9F%A9%E9%98%B5"><span class="toc-number">4.1.2.5.</span> <span class="toc-text">54. 螺旋矩阵</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#118-%E6%9D%A8%E8%BE%89%E4%B8%89%E8%A7%92"><span class="toc-number">4.1.2.6.</span> <span class="toc-text">118. 杨辉三角</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#67-%E4%BA%8C%E8%BF%9B%E5%88%B6%E6%B1%82%E5%92%8C"><span class="toc-number">4.1.2.7.</span> <span class="toc-text">67. 二进制求和</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#28-%E5%AE%9E%E7%8E%B0strStr"><span class="toc-number">4.1.2.8.</span> <span class="toc-text">28. 实现strStr()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#14-%E6%9C%80%E9%95%BF%E5%85%AC%E5%85%B1%E5%89%8D%E7%BC%80"><span class="toc-number">4.1.2.9.</span> <span class="toc-text">14. 最长公共前缀</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#344-%E5%8F%8D%E8%BD%AC%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-number">4.1.2.10.</span> <span class="toc-text">344. 反转字符串</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#561-%E6%95%B0%E7%BB%84%E6%8B%86%E5%88%86-I"><span class="toc-number">4.1.2.11.</span> <span class="toc-text">561. 数组拆分 I</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#167-%E4%B8%A4%E6%95%B0%E4%B9%8B%E5%92%8C-II-%E8%BE%93%E5%85%A5%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84"><span class="toc-number">4.1.2.12.</span> <span class="toc-text">167. 两数之和 II - 输入有序数组</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#27-%E7%A7%BB%E9%99%A4%E5%85%83%E7%B4%A0"><span class="toc-number">4.1.2.13.</span> <span class="toc-text">27. 移除元素</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#485-%E6%9C%80%E5%A4%A7%E8%BF%9E%E7%BB%AD1%E7%9A%84%E4%B8%AA%E6%95%B0"><span class="toc-number">4.1.2.14.</span> <span class="toc-text">485. 最大连续1的个数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#209-%E9%95%BF%E5%BA%A6%E6%9C%80%E5%B0%8F%E7%9A%84%E5%AD%90%E6%95%B0%E7%BB%84"><span class="toc-number">4.1.2.15.</span> <span class="toc-text">209. 长度最小的子数组</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#189-%E6%97%8B%E8%BD%AC%E6%95%B0%E7%BB%84"><span class="toc-number">4.1.2.16.</span> <span class="toc-text">189. 旋转数组</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#119-%E6%9D%A8%E8%BE%89%E4%B8%89%E8%A7%92-II"><span class="toc-number">4.1.2.17.</span> <span class="toc-text">119. 杨辉三角 II</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#151-%E7%BF%BB%E8%BD%AC%E5%AD%97%E7%AC%A6%E4%B8%B2%E9%87%8C%E7%9A%84%E5%8D%95%E8%AF%8D"><span class="toc-number">4.1.2.18.</span> <span class="toc-text">151. 翻转字符串里的单词</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#557-%E5%8F%8D%E8%BD%AC%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E7%9A%84%E5%8D%95%E8%AF%8D-III"><span class="toc-number">4.1.2.19.</span> <span class="toc-text">557. 反转字符串中的单词 III</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#26-%E5%88%A0%E9%99%A4%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84%E4%B8%AD%E7%9A%84%E9%87%8D%E5%A4%8D%E9%A1%B9"><span class="toc-number">4.1.2.20.</span> <span class="toc-text">26. 删除排序数组中的重复项</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#283-%E7%A7%BB%E5%8A%A8%E9%9B%B6"><span class="toc-number">4.1.2.21.</span> <span class="toc-text">283. 移动零</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%F0%9F%8C%A0-%E9%93%BE%E8%A1%A8"><span class="toc-number">4.1.3.</span> <span class="toc-text">🌠 链表</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#707-%E8%AE%BE%E8%AE%A1%E9%93%BE%E8%A1%A8"><span class="toc-number">4.1.3.1.</span> <span class="toc-text">707. 设计链表</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#141-%E7%8E%AF%E5%BD%A2%E9%93%BE%E8%A1%A8"><span class="toc-number">4.1.3.2.</span> <span class="toc-text">141. 环形链表</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#142-%E7%8E%AF%E5%BD%A2%E9%93%BE%E8%A1%A8-II"><span class="toc-number">4.1.3.3.</span> <span class="toc-text">142. 环形链表 II</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#160-%E7%9B%B8%E4%BA%A4%E9%93%BE%E8%A1%A8"><span class="toc-number">4.1.3.4.</span> <span class="toc-text">160. 相交链表</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#19-%E5%88%A0%E9%99%A4%E9%93%BE%E8%A1%A8%E7%9A%84%E5%80%92%E6%95%B0%E7%AC%ACN%E4%B8%AA%E8%8A%82%E7%82%B9"><span class="toc-number">4.1.3.5.</span> <span class="toc-text">19. 删除链表的倒数第N个节点</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#206-%E5%8F%8D%E8%BD%AC%E9%93%BE%E8%A1%A8"><span class="toc-number">4.1.3.6.</span> <span class="toc-text">206. 反转链表</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#203-%E7%A7%BB%E9%99%A4%E9%93%BE%E8%A1%A8%E5%85%83%E7%B4%A0"><span class="toc-number">4.1.3.7.</span> <span class="toc-text">203. 移除链表元素</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#328-%E5%A5%87%E5%81%B6%E9%93%BE%E8%A1%A8"><span class="toc-number">4.1.3.8.</span> <span class="toc-text">328. 奇偶链表</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#234-%E5%9B%9E%E6%96%87%E9%93%BE%E8%A1%A8"><span class="toc-number">4.1.3.9.</span> <span class="toc-text">234. 回文链表</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#21-%E5%90%88%E5%B9%B6%E4%B8%A4%E4%B8%AA%E6%9C%89%E5%BA%8F%E9%93%BE%E8%A1%A8"><span class="toc-number">4.1.3.10.</span> <span class="toc-text">21. 合并两个有序链表</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E4%B8%A4%E6%95%B0%E7%9B%B8%E5%8A%A0"><span class="toc-number">4.1.3.11.</span> <span class="toc-text">2. 两数相加</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#430-%E6%89%81%E5%B9%B3%E5%8C%96%E5%A4%9A%E7%BA%A7%E5%8F%8C%E5%90%91%E9%93%BE%E8%A1%A8"><span class="toc-number">4.1.3.12.</span> <span class="toc-text">430. 扁平化多级双向链表</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#138-%E5%A4%8D%E5%88%B6%E5%B8%A6%E9%9A%8F%E6%9C%BA%E6%8C%87%E9%92%88%E7%9A%84%E9%93%BE%E8%A1%A8"><span class="toc-number">4.1.3.13.</span> <span class="toc-text">138. 复制带随机指针的链表</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#61-%E6%97%8B%E8%BD%AC%E9%93%BE%E8%A1%A8"><span class="toc-number">4.1.3.14.</span> <span class="toc-text">61. 旋转链表</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%F0%9F%8C%A0-%E5%93%88%E5%B8%8C%E8%A1%A8"><span class="toc-number">4.1.4.</span> <span class="toc-text">🌠 哈希表</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#705-%E8%AE%BE%E8%AE%A1%E5%93%88%E5%B8%8C%E9%9B%86%E5%90%88"><span class="toc-number">4.1.4.1.</span> <span class="toc-text">705. 设计哈希集合</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#706-%E8%AE%BE%E8%AE%A1%E5%93%88%E5%B8%8C%E6%98%A0%E5%B0%84"><span class="toc-number">4.1.4.2.</span> <span class="toc-text">706. 设计哈希映射</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#217-%E5%AD%98%E5%9C%A8%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0"><span class="toc-number">4.1.4.3.</span> <span class="toc-text">217. 存在重复元素</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#136-%E5%8F%AA%E5%87%BA%E7%8E%B0%E4%B8%80%E6%AC%A1%E7%9A%84%E6%95%B0%E5%AD%97"><span class="toc-number">4.1.4.4.</span> <span class="toc-text">136. 只出现一次的数字</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#349-%E4%B8%A4%E4%B8%AA%E6%95%B0%E7%BB%84%E7%9A%84%E4%BA%A4%E9%9B%86"><span class="toc-number">4.1.4.5.</span> <span class="toc-text">349. 两个数组的交集</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#202-%E5%BF%AB%E4%B9%90%E6%95%B0"><span class="toc-number">4.1.4.6.</span> <span class="toc-text">202. 快乐数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E4%B8%A4%E6%95%B0%E4%B9%8B%E5%92%8C"><span class="toc-number">4.1.4.7.</span> <span class="toc-text">1. 两数之和</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#205-%E5%90%8C%E6%9E%84%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-number">4.1.4.8.</span> <span class="toc-text">205. 同构字符串</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#599-%E4%B8%A4%E4%B8%AA%E5%88%97%E8%A1%A8%E7%9A%84%E6%9C%80%E5%B0%8F%E7%B4%A2%E5%BC%95%E6%80%BB%E5%92%8C"><span class="toc-number">4.1.4.9.</span> <span class="toc-text">599. 两个列表的最小索引总和</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#387-%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E5%94%AF%E4%B8%80%E5%AD%97%E7%AC%A6"><span class="toc-number">4.1.4.10.</span> <span class="toc-text">387. 字符串中的第一个唯一字符</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#350-%E4%B8%A4%E4%B8%AA%E6%95%B0%E7%BB%84%E7%9A%84%E4%BA%A4%E9%9B%86-II"><span class="toc-number">4.1.4.11.</span> <span class="toc-text">350. 两个数组的交集 II</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#219-%E5%AD%98%E5%9C%A8%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0-II"><span class="toc-number">4.1.4.12.</span> <span class="toc-text">219. 存在重复元素 II</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#49-%E5%AD%97%E6%AF%8D%E5%BC%82%E4%BD%8D%E8%AF%8D%E5%88%86%E7%BB%84"><span class="toc-number">4.1.4.13.</span> <span class="toc-text">49. 字母异位词分组</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#36-%E6%9C%89%E6%95%88%E7%9A%84%E6%95%B0%E7%8B%AC"><span class="toc-number">4.1.4.14.</span> <span class="toc-text">36. 有效的数独</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#652-%E5%AF%BB%E6%89%BE%E9%87%8D%E5%A4%8D%E7%9A%84%E5%AD%90%E6%A0%91"><span class="toc-number">4.1.4.15.</span> <span class="toc-text">652. 寻找重复的子树</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#771-%E5%AE%9D%E7%9F%B3%E4%B8%8E%E7%9F%B3%E5%A4%B4"><span class="toc-number">4.1.4.16.</span> <span class="toc-text">771. 宝石与石头</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-%E6%97%A0%E9%87%8D%E5%A4%8D%E5%AD%97%E7%AC%A6%E7%9A%84%E6%9C%80%E9%95%BF%E5%AD%90%E4%B8%B2"><span class="toc-number">4.1.4.17.</span> <span class="toc-text">3. 无重复字符的最长子串</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#454-%E5%9B%9B%E6%95%B0%E7%9B%B8%E5%8A%A0-II"><span class="toc-number">4.1.4.18.</span> <span class="toc-text">454. 四数相加 II</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#347-%E5%89%8DK%E4%B8%AA%E9%AB%98%E9%A2%91%E5%85%83%E7%B4%A0"><span class="toc-number">4.1.4.19.</span> <span class="toc-text">347. 前K个高频元素</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#380-%E5%B8%B8%E6%95%B0%E6%97%B6%E9%97%B4%E6%8F%92%E5%85%A5%E3%80%81%E5%88%A0%E9%99%A4%E5%92%8C%E8%8E%B7%E5%8F%96%E9%9A%8F%E6%9C%BA%E5%85%83%E7%B4%A0"><span class="toc-number">4.1.4.20.</span> <span class="toc-text">380. 常数时间插入、删除和获取随机元素</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%F0%9F%8C%A0-%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE"><span class="toc-number">4.1.5.</span> <span class="toc-text">🌠 二分查找</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#704-%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE"><span class="toc-number">4.1.5.1.</span> <span class="toc-text">704. 二分查找</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#69-x-%E7%9A%84%E5%B9%B3%E6%96%B9%E6%A0%B9"><span class="toc-number">4.1.5.2.</span> <span class="toc-text">69. x 的平方根</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#374-%E7%8C%9C%E6%95%B0%E5%AD%97%E5%A4%A7%E5%B0%8F"><span class="toc-number">4.1.5.3.</span> <span class="toc-text">374. 猜数字大小</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#33-%E6%90%9C%E7%B4%A2%E6%97%8B%E8%BD%AC%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84"><span class="toc-number">4.1.5.4.</span> <span class="toc-text">33. 搜索旋转排序数组</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#278-%E7%AC%AC%E4%B8%80%E4%B8%AA%E9%94%99%E8%AF%AF%E7%9A%84%E7%89%88%E6%9C%AC"><span class="toc-number">4.1.5.5.</span> <span class="toc-text">278. 第一个错误的版本</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#162-%E5%AF%BB%E6%89%BE%E5%B3%B0%E5%80%BC"><span class="toc-number">4.1.5.6.</span> <span class="toc-text">162. 寻找峰值</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#153-%E5%AF%BB%E6%89%BE%E6%97%8B%E8%BD%AC%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84%E4%B8%AD%E7%9A%84%E6%9C%80%E5%B0%8F%E5%80%BC"><span class="toc-number">4.1.5.7.</span> <span class="toc-text">153. 寻找旋转排序数组中的最小值</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#34-%E5%9C%A8%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84%E4%B8%AD%E6%9F%A5%E6%89%BE%E5%85%83%E7%B4%A0%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E5%92%8C%E6%9C%80%E5%90%8E%E4%B8%80%E4%B8%AA%E4%BD%8D%E7%BD%AE-1"><span class="toc-number">4.1.5.8.</span> <span class="toc-text">34. 在排序数组中查找元素的第一个和最后一个位置</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#658-%E6%89%BE%E5%88%B0-K-%E4%B8%AA%E6%9C%80%E6%8E%A5%E8%BF%91%E7%9A%84%E5%85%83%E7%B4%A0"><span class="toc-number">4.1.5.9.</span> <span class="toc-text">658. 找到 K 个最接近的元素</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#162-%E5%AF%BB%E6%89%BE%E5%B3%B0%E5%80%BC-1"><span class="toc-number">4.1.5.10.</span> <span class="toc-text">162. 寻找峰值</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#50-Pow-x-n"><span class="toc-number">4.1.5.11.</span> <span class="toc-text">50. Pow(x, n)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#367-%E6%9C%89%E6%95%88%E7%9A%84%E5%AE%8C%E5%85%A8%E5%B9%B3%E6%96%B9%E6%95%B0"><span class="toc-number">4.1.5.12.</span> <span class="toc-text">367. 有效的完全平方数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#744-%E5%AF%BB%E6%89%BE%E6%AF%94%E7%9B%AE%E6%A0%87%E5%AD%97%E6%AF%8D%E5%A4%A7%E7%9A%84%E6%9C%80%E5%B0%8F%E5%AD%97%E6%AF%8D"><span class="toc-number">4.1.5.13.</span> <span class="toc-text">744. 寻找比目标字母大的最小字母</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#153-%E5%AF%BB%E6%89%BE%E6%97%8B%E8%BD%AC%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84%E4%B8%AD%E7%9A%84%E6%9C%80%E5%B0%8F%E5%80%BC-1"><span class="toc-number">4.1.5.14.</span> <span class="toc-text">153. 寻找旋转排序数组中的最小值</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#154-%E5%AF%BB%E6%89%BE%E6%97%8B%E8%BD%AC%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84%E4%B8%AD%E7%9A%84%E6%9C%80%E5%B0%8F%E5%80%BC-II"><span class="toc-number">4.1.5.15.</span> <span class="toc-text">154. 寻找旋转排序数组中的最小值 II</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#349-%E4%B8%A4%E4%B8%AA%E6%95%B0%E7%BB%84%E7%9A%84%E4%BA%A4%E9%9B%86-1"><span class="toc-number">4.1.5.16.</span> <span class="toc-text">349. 两个数组的交集</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#350-%E4%B8%A4%E4%B8%AA%E6%95%B0%E7%BB%84%E7%9A%84%E4%BA%A4%E9%9B%86-II-1"><span class="toc-number">4.1.5.17.</span> <span class="toc-text">350. 两个数组的交集 II</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#167-%E4%B8%A4%E6%95%B0%E4%B9%8B%E5%92%8C-II-%E8%BE%93%E5%85%A5%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84-1"><span class="toc-number">4.1.5.18.</span> <span class="toc-text">167. 两数之和 II - 输入有序数组</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#287-%E5%AF%BB%E6%89%BE%E9%87%8D%E5%A4%8D%E6%95%B0"><span class="toc-number">4.1.5.19.</span> <span class="toc-text">287. 寻找重复数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-%E5%AF%BB%E6%89%BE%E4%B8%A4%E4%B8%AA%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84%E7%9A%84%E4%B8%AD%E4%BD%8D%E6%95%B0"><span class="toc-number">4.1.5.20.</span> <span class="toc-text">4. 寻找两个有序数组的中位数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#719-%E6%89%BE%E5%87%BA%E7%AC%AC-k-%E5%B0%8F%E7%9A%84%E8%B7%9D%E7%A6%BB%E5%AF%B9"><span class="toc-number">4.1.5.21.</span> <span class="toc-text">719. 找出第 k 小的距离对</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#410-%E5%88%86%E5%89%B2%E6%95%B0%E7%BB%84%E7%9A%84%E6%9C%80%E5%A4%A7%E5%80%BC"><span class="toc-number">4.1.5.22.</span> <span class="toc-text">410. 分割数组的最大值</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%F0%9F%8C%A0-%E4%BA%8C%E5%8F%89%E6%A0%91"><span class="toc-number">4.1.6.</span> <span class="toc-text">🌠 二叉树</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#144-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%89%8D%E5%BA%8F%E9%81%8D%E5%8E%86"><span class="toc-number">4.1.6.1.</span> <span class="toc-text">144. 二叉树的前序遍历</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#94-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E4%B8%AD%E5%BA%8F%E9%81%8D%E5%8E%86-1"><span class="toc-number">4.1.6.2.</span> <span class="toc-text">94. 二叉树的中序遍历</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#145-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86"><span class="toc-number">4.1.6.3.</span> <span class="toc-text">145. 二叉树的后序遍历</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#102-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%B1%82%E6%AC%A1%E9%81%8D%E5%8E%86"><span class="toc-number">4.1.6.4.</span> <span class="toc-text">102. 二叉树的层次遍历</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#104-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6"><span class="toc-number">4.1.6.5.</span> <span class="toc-text">104. 二叉树的最大深度</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#101-%E5%AF%B9%E7%A7%B0%E4%BA%8C%E5%8F%89%E6%A0%91"><span class="toc-number">4.1.6.6.</span> <span class="toc-text">101. 对称二叉树</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#112-%E8%B7%AF%E5%BE%84%E6%80%BB%E5%92%8C"><span class="toc-number">4.1.6.7.</span> <span class="toc-text">112. 路径总和</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#106-%E4%BB%8E%E4%B8%AD%E5%BA%8F%E4%B8%8E%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86%E5%BA%8F%E5%88%97%E6%9E%84%E9%80%A0%E4%BA%8C%E5%8F%89%E6%A0%91"><span class="toc-number">4.1.6.8.</span> <span class="toc-text">106. 从中序与后序遍历序列构造二叉树</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#105-%E4%BB%8E%E5%89%8D%E5%BA%8F%E4%B8%8E%E4%B8%AD%E5%BA%8F%E9%81%8D%E5%8E%86%E5%BA%8F%E5%88%97%E6%9E%84%E9%80%A0%E4%BA%8C%E5%8F%89%E6%A0%91"><span class="toc-number">4.1.6.9.</span> <span class="toc-text">105. 从前序与中序遍历序列构造二叉树</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#116-%E5%A1%AB%E5%85%85%E6%AF%8F%E4%B8%AA%E8%8A%82%E7%82%B9%E7%9A%84%E4%B8%8B%E4%B8%80%E4%B8%AA%E5%8F%B3%E4%BE%A7%E8%8A%82%E7%82%B9%E6%8C%87%E9%92%88"><span class="toc-number">4.1.6.10.</span> <span class="toc-text">116. 填充每个节点的下一个右侧节点指针</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#117-%E5%A1%AB%E5%85%85%E6%AF%8F%E4%B8%AA%E8%8A%82%E7%82%B9%E7%9A%84%E4%B8%8B%E4%B8%80%E4%B8%AA%E5%8F%B3%E4%BE%A7%E8%8A%82%E7%82%B9%E6%8C%87%E9%92%88-II"><span class="toc-number">4.1.6.11.</span> <span class="toc-text">117. 填充每个节点的下一个右侧节点指针 II</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#236-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88"><span class="toc-number">4.1.6.12.</span> <span class="toc-text">236. 二叉树的最近公共祖先</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#297-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%BA%8F%E5%88%97%E5%8C%96%E4%B8%8E%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96"><span class="toc-number">4.1.6.13.</span> <span class="toc-text">297. 二叉树的序列化与反序列化</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%F0%9F%8C%A0-%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91"><span class="toc-number">4.1.7.</span> <span class="toc-text">🌠 二叉搜索树</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#98-%E9%AA%8C%E8%AF%81%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91"><span class="toc-number">4.1.7.1.</span> <span class="toc-text">98. 验证二叉搜索树</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#173-%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E8%BF%AD%E4%BB%A3%E5%99%A8"><span class="toc-number">4.1.7.2.</span> <span class="toc-text">173. 二叉搜索树迭代器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#700-%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E4%B8%AD%E7%9A%84%E6%90%9C%E7%B4%A2"><span class="toc-number">4.1.7.3.</span> <span class="toc-text">700. 二叉搜索树中的搜索</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#701-%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E4%B8%AD%E7%9A%84%E6%8F%92%E5%85%A5%E6%93%8D%E4%BD%9C"><span class="toc-number">4.1.7.4.</span> <span class="toc-text">701. 二叉搜索树中的插入操作</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#450-%E5%88%A0%E9%99%A4%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E4%B8%AD%E7%9A%84%E8%8A%82%E7%82%B9"><span class="toc-number">4.1.7.5.</span> <span class="toc-text">450. 删除二叉搜索树中的节点</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#703-%E6%95%B0%E6%8D%AE%E6%B5%81%E4%B8%AD%E7%9A%84%E7%AC%ACK%E5%A4%A7%E5%85%83%E7%B4%A0"><span class="toc-number">4.1.7.6.</span> <span class="toc-text">703. 数据流中的第K大元素</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#236-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88-1"><span class="toc-number">4.1.7.7.</span> <span class="toc-text">236. 二叉树的最近公共祖先</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#220-%E5%AD%98%E5%9C%A8%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0-III"><span class="toc-number">4.1.7.8.</span> <span class="toc-text">220. 存在重复元素 III</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#110-%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91"><span class="toc-number">4.1.7.9.</span> <span class="toc-text">110. 平衡二叉树</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#108-%E5%B0%86%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84%E8%BD%AC%E6%8D%A2%E4%B8%BA%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91"><span class="toc-number">4.1.7.10.</span> <span class="toc-text">108. 将有序数组转换为二叉搜索树</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%F0%9F%8C%A0-N%E5%8F%89%E6%A0%91"><span class="toc-number">4.1.8.</span> <span class="toc-text">🌠 N叉树</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#589-N%E5%8F%89%E6%A0%91%E7%9A%84%E5%89%8D%E5%BA%8F%E9%81%8D%E5%8E%86"><span class="toc-number">4.1.8.1.</span> <span class="toc-text">589. N叉树的前序遍历</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#590-N-ary-Tree-Postorder-Traversal"><span class="toc-number">4.1.8.2.</span> <span class="toc-text">590. N-ary Tree Postorder Traversal</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#429-N%E5%8F%89%E6%A0%91%E7%9A%84%E5%B1%82%E5%BA%8F%E9%81%8D%E5%8E%86"><span class="toc-number">4.1.8.3.</span> <span class="toc-text">429. N叉树的层序遍历</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#559-N%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6"><span class="toc-number">4.1.8.4.</span> <span class="toc-text">559. N叉树的最大深度</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%B2%BE%E9%80%89"><span class="toc-number">4.2.</span> <span class="toc-text">精选</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%F0%9F%8C%A0-%E9%80%92%E5%BD%92-I"><span class="toc-number">4.2.1.</span> <span class="toc-text">🌠 递归 I</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#344-%E5%8F%8D%E8%BD%AC%E5%AD%97%E7%AC%A6%E4%B8%B2-1"><span class="toc-number">4.2.1.1.</span> <span class="toc-text">344. 反转字符串</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#24-%E4%B8%A4%E4%B8%A4%E4%BA%A4%E6%8D%A2%E9%93%BE%E8%A1%A8%E4%B8%AD%E7%9A%84%E8%8A%82%E7%82%B9"><span class="toc-number">4.2.1.2.</span> <span class="toc-text">24. 两两交换链表中的节点</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#118-%E6%9D%A8%E8%BE%89%E4%B8%89%E8%A7%92-1"><span class="toc-number">4.2.1.3.</span> <span class="toc-text">118. 杨辉三角</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#119-%E6%9D%A8%E8%BE%89%E4%B8%89%E8%A7%92-II-1"><span class="toc-number">4.2.1.4.</span> <span class="toc-text">119. 杨辉三角 II</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#206-%E5%8F%8D%E8%BD%AC%E9%93%BE%E8%A1%A8-1"><span class="toc-number">4.2.1.5.</span> <span class="toc-text">206. 反转链表</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#509-%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0"><span class="toc-number">4.2.1.6.</span> <span class="toc-text">509. 斐波那契数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#70-%E7%88%AC%E6%A5%BC%E6%A2%AF"><span class="toc-number">4.2.1.7.</span> <span class="toc-text">70. 爬楼梯</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#104-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6-1"><span class="toc-number">4.2.1.8.</span> <span class="toc-text">104. 二叉树的最大深度</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#50-Pow-x-n-1"><span class="toc-number">4.2.1.9.</span> <span class="toc-text">50. Pow(x, n)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#21-%E5%90%88%E5%B9%B6%E4%B8%A4%E4%B8%AA%E6%9C%89%E5%BA%8F%E9%93%BE%E8%A1%A8-1"><span class="toc-number">4.2.1.10.</span> <span class="toc-text">21. 合并两个有序链表</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#779-%E7%AC%ACK%E4%B8%AA%E8%AF%AD%E6%B3%95%E7%AC%A6%E5%8F%B7"><span class="toc-number">4.2.1.11.</span> <span class="toc-text">779. 第K个语法符号</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#95-%E4%B8%8D%E5%90%8C%E7%9A%84%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91-II"><span class="toc-number">4.2.1.12.</span> <span class="toc-text">95. 不同的二叉搜索树 II</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%B8%B8%E7%94%A8%E6%8A%80%E5%B7%A7%E6%80%BB%E7%BB%93"><span class="toc-number">5.</span> <span class="toc-text">常用技巧总结</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E9%9A%90%E8%97%8F%E7%9A%84%E5%9D%91"><span class="toc-number">6.</span> <span class="toc-text">隐藏的坑</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E8%A7%A3%E6%B3%95%E6%B1%87%E6%80%BB%E8%B4%A1%E7%8C%AE%E8%80%85"><span class="toc-number">7.</span> <span class="toc-text">解法汇总贡献者</span></a></li></ol>
    </nav>
  </div>
</aside>

<main class="main" role="main">
  <div class="content">
  <article id="post-shortest-leetcode-python-solutions" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      力扣简洁优雅的python解法
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar"></i>
	<a href="/20200604/shortest-leetcode-python-solutions.html" class="article-date">
	  发布于 <time datetime="2020-06-04T13:32:55.000Z" itemprop="datePublished">2020-06-04</time>
	</a>
</span>
<span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/20200604/shortest-leetcode-python-solutions.html" class="article-date">
	  更新于 <time datetime="2020-06-05T03:42:18.000Z" itemprop="dateUpdated">2020-06-05</time>
	</a>
</span>
        
  <span class="article-category">
    <i class="icon icon-folder"></i>
    <a class="article-category-link" href="/categories/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/">数据结构与算法</a>
  </span>

        
  <span class="article-tag">
    <i class="icon icon-tags"></i>
	<a class="article-tag-link-link" href="/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" rel="tag">数据结构与算法</a>
  </span>


        

	<span class="article-read hidden-xs">
    	<i class="icon icon-eye-fill" aria-hidden="true"></i>
    	<span id="/20200604/shortest-leetcode-python-solutions.html" class="leancloud_visitors"  data-flag-title="力扣简洁优雅的python解法">
			<span class="leancloud-visitors-count">0</span>
		</span>
    </span>

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/20200604/shortest-leetcode-python-solutions.html#comments" class="article-comment-link">评论</a></span>
        
	
		<span class="post-wordcount hidden-xs" itemprop="wordCount">字数统计: 41.1k(字)</span>
	
	
		<span class="post-readcount hidden-xs" itemprop="timeRequired">阅读时长: 198(分)</span>
	

      </div>
      <div style="background-color:#D7BDE2;border:1px solid #D7BDE2;border-radius:10px;padding:5px">
          <b>温馨提示</b>：点击页面下方<i style="color:red" class="icon icon-anchor"></i>以展开或折叠目录
      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <p>摘要：<code>Python</code>语言特点之一就是优雅简洁，为方便学习数据结构，搬运自Github<a target="_blank" rel="noopener" href="https://github.com/cy69855522/Shortest-LeetCode-Python-Solutions">【项目地址】</a>上汇总<code>LeetCode</code>最短最优雅的解法的项目。<span id="more"></span></p>
<blockquote>
<p><font size=5><b>文章说明</b></font><br><strong>文章来源：</strong><a target="_blank" rel="noopener" href="https://github.com/cy69855522/Shortest-LeetCode-Python-Solutions">Shortest-LeetCode-Python-Solutions</a><br><strong>文章作者：</strong><a target="_blank" rel="noopener" href="https://github.com/cy69855522">Knife丶</a><br><strong>原文链接：</strong><a target="_blank" rel="noopener" href="https://github.com/cy69855522/Shortest-LeetCode-Python-Solutions">https://github.com/cy69855522/Shortest-LeetCode-Python-Solutions</a><br><strong>文章说明：</strong>方便学习数据结构，搬运自<a target="_blank" rel="noopener" href="https://github.com/cy69855522/Shortest-LeetCode-Python-Solutions">Github</a></p>
</blockquote>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><ul>
<li>Leet Code 刷题笔记 - - 不求最快最省，但求最短最优雅 :herb:，Shorter is better here.</li>
<li>代码精炼是 Python 的核心，同时能够反应对于语言的熟练程度，本项目目的在于汇总 leet code 最短最优雅的解法，拒绝长篇大论，缩短学习周期，掌握各种技巧，助您在面试中写出令人眼前一亮的解答，给考官留个好印象。</li>
<li>为什么我们追求最短?</li>
<li><ul>
<li><strong>1.</strong>短代码更pythonic，而且通常能够避免一些冗余过程。</li>
</ul>
</li>
<li><ul>
<li><strong>2.</strong>除了刷题掌握算法思路之外，我们更追求深入理解和掌握python,学会套用技巧，举一反三。</li>
</ul>
</li>
<li><ul>
<li><strong>3.</strong>真正面试的时候不一定要这么短，可以适当展开几行(O_o 除非你就是想秀其他人一脸 😅)，保证思路更清晰，相信就算展开几行也会比其他题解短很多吧。</li>
</ul>
</li>
<li><ul>
<li><strong>4.</strong>刷题很累，找点乐子，送给自己一些成就感吧。</li>
</ul>
</li>
<li><ul>
<li><strong>5.</strong>所有已收录代码都是优中选优，题库解析部分除了短代码外，也有常规解法作为补充。</li>
</ul>
</li>
<li><ul>
<li><strong>6.</strong>若基础知识不够扎实，可以先看<a href="#专题探索"><strong>专题探索</strong></a>部分，然后再转<a href="#题库解析"><strong>题库解析</strong></a>学习 Python 中隐藏的先进技巧。</li>
</ul>
</li>
<li>项目持续更新中，优先使用 python3，不支持的题目使用 python2 代替，如果您有更短更优雅的解法希望分享的话欢迎联系更新~  [直接发issue 或 fork，记得留下署名和联系方式~~] 鉴于追求的主题，此项目收录 1.在代码量(不是行数)上明显优于现有解的最短代码 2.思路更高效的一般解法（作为补充放在首选解之后） [题目自带的代码不计入代码量]</li>
<li>如果您对当前解析有任何疑问，咱们 issue 见~</li>
<li>由于CSDN博客更新需要人工审核比较慢，所以迁移到github上，优先更新github内容。</li>
<li>为了快速找到题目可以按 [<strong>Ctrl键 + F键</strong>] 输入题目序号或名字定位。</li>
<li>欢迎加入<strong>QQ交流群</strong>：902025048 <a href="QR.png">∷二维码</a> 群内提供更多相关资料~<h1 id="里程碑"><a href="#里程碑" class="headerlink" title="里程碑"></a>里程碑</h1></li>
<li><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problemset/all/?listId=ex0k24j">腾讯精选练习</a>（50题: 25简单 21中等 4困难） 代码行数 总计：140行 平均：2.8行 【2019/05/05】</li>
<li>🧬 数据结构<ul>
<li><a href="#-%E9%98%9F%E5%88%97--%E6%A0%88">🐤 队列 &amp; 栈</a>（5 章节 32 栏目） 高可读，不含VIP解锁题 <a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/queue-stack/">题目详情</a> 2019/05/31</li>
<li><a href="#-%E6%95%B0%E7%BB%84%E5%92%8C%E5%AD%97%E7%AC%A6%E4%B8%B2">🐑 数组和字符串</a>（5 章节 29 栏目） 高可读 <a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/queue-stack/">题目详情</a> 2019/06/15</li>
<li><a href="#-%E9%93%BE%E8%A1%A8">🦌 链表</a>（5 章节 26 栏目） 高可读 <a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/linked-list/197/conclusion/">题目详情</a> 2019/06/25</li>
<li><a href="#-%E5%93%88%E5%B8%8C%E8%A1%A8">🦎 哈希表</a>（5 章节 35 栏目） 高可读，不含VIP解锁题 <a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/linked-list/197/conclusion/">题目详情</a> 2019/07/07</li>
<li><a href="#-%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE">🐄 二分查找</a>（8 章节 30 栏目） 高可读，不含VIP解锁题 <a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/binary-search/">题目详情</a> 2019/07/30</li>
<li><a href="#-%E4%BA%8C%E5%8F%89%E6%A0%91">🦉 二叉树</a>（3 章节 16 栏目） 高可读 <a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/data-structure-binary-tree/">题目详情</a> 2019/09/21</li>
<li><a href="#-%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91">🐦 二叉搜索树</a>（3 章节 16 栏目） 高可读 <a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/introduction-to-data-structure-binary-search-tree/">题目详情</a> 2019/11/15</li>
<li><a href="#-n%E5%8F%89%E6%A0%91">🐈 N叉树</a>（3 章节 7 栏目） 高可读，不含VIP解锁题 <a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/n-ary-tree/">题目详情</a> 2019/11/17</li>
</ul>
</li>
<li>⏱ <a href="#-%E9%80%92%E5%BD%92-i">递归 I</a>（5 章节 28 栏目） 高可读 <a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/featured/card/recursion-i/">题目详情</a> 2019/11/28</li>
</ul>
<h2 id="推荐"><a href="#推荐" class="headerlink" title="推荐"></a>推荐</h2><ul>
<li>👻<a target="_blank" rel="noopener" href="https://github.com/cy69855522/Simplest-LeetCode-Cpp-Solutions"> Leetcode最简C++题解 </a></li>
<li>🎃<a target="_blank" rel="noopener" href="https://github.com/cy69855522/Clearest-LeetCode-Cpp-Solutions"> C++清晰题解汇总 </a></li>
<li><a target="_blank" rel="noopener" href="https://www.aipower.xyz">🚀 AI Power</a> 云GPU租借/出租平台：Python是AI的核心，GPU是AI的动力，想要朝AI工程师发展的朋友不妨了解一下~ 现在注册并绑定（参考Github）即可获得高额算力，注册不涉及个人隐私信息，奖励可随时提现。详情请参考<a target="_blank" rel="noopener" href="https://github.com/cy69855522/AI-Power">AI Power指南</a></li>
<li>🌟 推荐刷题路线：<a href="#专题探索"><strong>专题探索</strong></a> → <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problemset/all/?listId=ex0k24j">腾讯精选50题</a> → <a href="#题库解析">题库解析</a><h1 id="题库解析"><a href="#题库解析" class="headerlink" title="题库解析"></a>题库解析</h1>此专栏追求代码的<strong>精简</strong>和<strong>技巧性</strong>，默认已看过题目，🤡 没看过的话点标题可以跳转链接，咱们一起体验炫酷的 Python<h2 id="1-Two-Sum-4行"><a href="#1-Two-Sum-4行" class="headerlink" title="1. Two Sum 4行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/two-sum/">1. Two Sum 4行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">twoSum</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], target: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">	d = &#123;&#125;</span><br><span class="line">	<span class="keyword">for</span> i, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(nums): </span><br><span class="line">	    <span class="keyword">if</span> n <span class="keyword">in</span> d: <span class="keyword">return</span> [d[n], i]</span><br><span class="line">	    d[target-n] = i</span><br></pre></td></tr></table></figure></li>
<li>$O(N)$时间效率的快速解法，用字典记录 <code>｛需要的值:当前索引｝</code><h2 id="2-Add-Two-Numbers-5行"><a href="#2-Add-Two-Numbers-5行" class="headerlink" title="2. Add Two Numbers 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/add-two-numbers/">2. Add Two Numbers 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">addTwoNumbers</span>(<span class="params">self, l1: ListNode, l2: ListNode, carry=<span class="number">0</span></span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> (l1 <span class="keyword">or</span> l2): <span class="keyword">return</span> ListNode(<span class="number">1</span>) <span class="keyword">if</span> carry <span class="keyword">else</span> <span class="literal">None</span></span><br><span class="line">        l1, l2 = l1 <span class="keyword">or</span> ListNode(<span class="number">0</span>), l2 <span class="keyword">or</span> ListNode(<span class="number">0</span>)</span><br><span class="line">        val = l1.val + l2.val + carry</span><br><span class="line">        l1.val, l1.<span class="built_in">next</span> = val % <span class="number">10</span>, self.addTwoNumbers(l1.<span class="built_in">next</span>, l2.<span class="built_in">next</span>, val &gt; <span class="number">9</span>)</span><br><span class="line">        <span class="keyword">return</span> l1</span><br></pre></td></tr></table></figure></li>
<li><code>int(True)</code> 等于 1</li>
<li><code>None or 7</code> 等于 7</li>
<li>用 <code>carry</code> 记录是否应该进位<h2 id="3-Longest-Substring-Without-Repeating-Characters-3行"><a href="#3-Longest-Substring-Without-Repeating-Characters-3行" class="headerlink" title="3. Longest Substring Without Repeating Characters 3行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/longest-substring-without-repeating-characters/">3. Longest Substring Without Repeating Characters 3行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">lengthOfLongestSubstring</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        i, r, d = <span class="number">0</span>, <span class="number">0</span>, &#123;&#125;</span><br><span class="line">        <span class="keyword">for</span> j, c <span class="keyword">in</span> <span class="built_in">enumerate</span>(s): i, r, d[c] = <span class="built_in">max</span>(i, d.get(c, -<span class="number">1</span>) + <span class="number">1</span>), <span class="built_in">max</span>(r, j - i), j</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">max</span>(r, <span class="built_in">len</span>(s) - i)</span><br></pre></td></tr></table></figure></li>
<li>双指针滑动窗口</li>
<li>i 代表起始位置，r 记录最优解，d 是一个字典，记录所有字符最后出现的位置</li>
<li>每次迭代过程中，遇到遇见过的字符时，i 就会变为那个字符上一次出现位置 + 1，r 记录上一次应该达到的全局最大值，所以最后需要再比较一次<h2 id="4-Median-of-Two-Sorted-Arrays-5行"><a href="#4-Median-of-Two-Sorted-Arrays-5行" class="headerlink" title="4. Median of Two Sorted Arrays 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/median-of-two-sorted-arrays/">4. Median of Two Sorted Arrays 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findMedianSortedArrays</span>(<span class="params">self, nums1: <span class="type">List</span>[<span class="built_in">int</span>], nums2: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">float</span>:</span><br><span class="line">        a, b, m = *<span class="built_in">sorted</span>((nums1, nums2), key=<span class="built_in">len</span>), (<span class="built_in">len</span>(nums1) + <span class="built_in">len</span>(nums2) - <span class="number">1</span>) // <span class="number">2</span></span><br><span class="line">        self.__class__.__getitem__ = <span class="keyword">lambda</span> self, i: m-i-<span class="number">1</span> &lt; <span class="number">0</span> <span class="keyword">or</span> a[i] &gt;= b[m-i-<span class="number">1</span>]</span><br><span class="line">        i = bisect.bisect_left(self, <span class="literal">True</span>, <span class="number">0</span>, <span class="built_in">len</span>(a))</span><br><span class="line">        r = <span class="built_in">sorted</span>(a[i:i+<span class="number">2</span>] + b[m-i:m-i+<span class="number">2</span>])</span><br><span class="line">        <span class="keyword">return</span> (r[<span class="number">0</span>] + r[<span class="number">1</span> - (<span class="built_in">len</span>(a) + <span class="built_in">len</span>(b)) % <span class="number">2</span>]) / <span class="number">2</span></span><br></pre></td></tr></table></figure></li>
<li>本题思路与官方题解类似，时间复杂度$O(\log(\min(m, n)))$，没看过的话建议先大体了解一下</li>
<li>python 中 bisect 模块针对的是 list, 如果直接构造 list，时间复杂度为 $O(\min(m, n))$，因此我们修改当前类的魔法方法伪造 list</li>
<li>在一个有序递增数列中，中位数左边的那部分的最大值一定小于或等于右边部分的最小值</li>
<li>如果总数组长度为奇数，m 代表中位数的索引，否则 m 代表用于计算中位数的那两个数字的左边一个。比如输入为[1,2]，[3]，那么m应该为[1,2,3]中位数2的索引1，如果输入为[1,3]，[2,4]，那么m应该为[1,2,3,4]中2的索引1</li>
<li>使用二分搜索找到 m 对应的值在a或b中对应的索引，也就是说，我们要找的中位数或中位数左部应该是 a[i] 或者 b[m-i]</li>
<li><code>bisect.bisect_left</code> 搜索列表中保持列表升序的情况下，True应该插入的位置（从左侧），比如 [F,F,T] 返回 2，[F,F] 返回 2</li>
<li>这里保证 a 是 nums1 和 nums2 中较短的那个，是为了防止二分搜索的时候索引越界</li>
<li>sorted返回一个list，假设返回值是 [nums1, nums2]，那么前面加个 * 号就代表取出列表的所有内容，相当于一个迭代器，结果相当于直接写 nums1, nums2<h2 id="5-Longest-Palindromic-Substring-5行"><a href="#5-Longest-Palindromic-Substring-5行" class="headerlink" title="5. Longest Palindromic Substring 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/longest-palindromic-substring/">5. Longest Palindromic Substring 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">longestPalindrome</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        r = <span class="string">&#x27;&#x27;</span></span><br><span class="line">        <span class="keyword">for</span> i, j <span class="keyword">in</span> [(i, j) <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(s)) <span class="keyword">for</span> j <span class="keyword">in</span> (<span class="number">0</span>, <span class="number">1</span>)]:</span><br><span class="line">            <span class="keyword">while</span> i &gt; -<span class="number">1</span> <span class="keyword">and</span> i + j &lt; <span class="built_in">len</span>(s) <span class="keyword">and</span> s[i] == s[i + j]: i, j = i - <span class="number">1</span>, j + <span class="number">2</span></span><br><span class="line">            r = <span class="built_in">max</span>(r, s[i + <span class="number">1</span>:i + j], key=<span class="built_in">len</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;&#x27;</span> <span class="keyword">if</span> <span class="keyword">not</span> s <span class="keyword">else</span> r</span><br></pre></td></tr></table></figure></li>
<li>遍历字符串的每个索引 i，判断能否以 s[i] 或 s[i:i+j+1] 为中心向往拓展回文字符串<h2 id="7-Reverse-Integer-2行"><a href="#7-Reverse-Integer-2行" class="headerlink" title="7. Reverse Integer 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/reverse-integer/">7. Reverse Integer 2行</a></h2></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">reverse</span>(<span class="params">self, x</span>):</span><br><span class="line">        r = x // <span class="built_in">max</span>(<span class="number">1</span>, <span class="built_in">abs</span>(x)) * <span class="built_in">int</span>(<span class="built_in">str</span>(<span class="built_in">abs</span>(x))[::-<span class="number">1</span>])</span><br><span class="line">        <span class="keyword">return</span> r <span class="keyword">if</span> r.bit_length() &lt; <span class="number">32</span> <span class="keyword">or</span> r == -<span class="number">2</span>**<span class="number">31</span> <span class="keyword">else</span> <span class="number">0</span></span><br></pre></td></tr></table></figure>
<ul>
<li><code>x // max(1, abs(x))</code>意味着 0：x为0， 1：x为正， -1：x为负，相当于被废弃的函数<code>cmp</code></li>
<li>[::-1]代表序列反转</li>
<li>$2^{31}$ 和 $-2^{31}$ 的比特数为32，其中正负号占用了一位</li>
<li>32位整数范围 $[−2^{31}, \; 2^{31} − 1]$ 中正数范围小一个是因为0的存在<h2 id="8-String-to-Integer-atoi-1行"><a href="#8-String-to-Integer-atoi-1行" class="headerlink" title="8. String to Integer (atoi) 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/string-to-integer-atoi/">8. String to Integer (atoi) 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">myAtoi</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">max</span>(<span class="built_in">min</span>(<span class="built_in">int</span>(*re.findall(<span class="string">&#x27;^[\+\-]?\d+&#x27;</span>, s.lstrip())), <span class="number">2</span>**<span class="number">31</span> - <span class="number">1</span>), -<span class="number">2</span>**<span class="number">31</span>)</span><br></pre></td></tr></table></figure></li>
<li>使用正则表达式 <code>^：匹配字符串开头，[\+\-]：代表一个+字符或-字符，?：前面一个字符可有可无，\d：一个数字，+：前面一个字符的一个或多个，\D：一个非数字字符</code></li>
<li><code>max(min(数字, 2**31 - 1), -2**31)</code> 用来防止结果越界<h2 id="9-Palindrome-Number-1行"><a href="#9-Palindrome-Number-1行" class="headerlink" title="9. Palindrome Number 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/palindrome-number/">9. Palindrome Number 1行</a></h2></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isPalindrome</span>(<span class="params">self, x: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">str</span>(x) == <span class="built_in">str</span>(x)[::-<span class="number">1</span>]</span><br></pre></td></tr></table></figure>
<p>不使用字符串的进阶解法：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isPalindrome</span>(<span class="params">self, x: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        r = <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="keyword">lambda</span> i: <span class="built_in">int</span>(<span class="number">10</span>**-i * x % <span class="number">10</span>), <span class="built_in">range</span>(<span class="built_in">int</span>(math.log10(x)), -<span class="number">1</span>, -<span class="number">1</span>))) <span class="keyword">if</span> x &gt; <span class="number">0</span> <span class="keyword">else</span> [<span class="number">0</span>, x]</span><br><span class="line">        <span class="keyword">return</span> r == r[::-<span class="number">1</span>]</span><br></pre></td></tr></table></figure>
<ul>
<li>思路是一样的，这里把整数转成了列表而不是字符串</li>
<li>比如一个整数$12321$，我想取出百位数可以这么做：$12321 * 10^{\text{int}(\log_{10}12321)} % 10 = 123 % 10 = 3$<h2 id="11-Container-With-Most-Water-3行"><a href="#11-Container-With-Most-Water-3行" class="headerlink" title="11. Container With Most Water 3行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/container-with-most-water/">11. Container With Most Water 3行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">maxArea</span>(<span class="params">self, height: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        res, l, r = <span class="number">0</span>, <span class="number">0</span>, <span class="built_in">len</span>(height) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> l &lt; r: res, l, r = (<span class="built_in">max</span>(res,  height[l] * (r - l)), l + <span class="number">1</span>, r) <span class="keyword">if</span> height[l] &lt; height[r] <span class="keyword">else</span> (<span class="built_in">max</span>(res,  height[r] * (r - l)), l, r - <span class="number">1</span>)</span><br><span class="line">        <span class="keyword">return</span> res</span><br></pre></td></tr></table></figure></li>
<li>双指针 $O(N)$ 解法</li>
<li>res：结果，l：容器左壁索引，r：容器右壁索引</li>
<li>如果 <code>height[l] &lt; height[r]</code> 那么 <code>l += 1</code> 否则 <code>r -= 1</code>，说明：如果 <code>height[0] &lt; height[3]</code> 那么(0, 1), (0, 2)对应的容器体积一定小于(0, 3)的，因为此时计算体积的时候高为 <code>height(0)</code>，容器的宽减少而高不增加，面积必然缩小<h2 id="13-Roman-to-Integer-2行"><a href="#13-Roman-to-Integer-2行" class="headerlink" title="13. Roman to Integer 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/roman-to-integer/">13. Roman to Integer 2行</a></h2></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">romanToInt</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        d = &#123;<span class="string">&#x27;I&#x27;</span>:<span class="number">1</span>, <span class="string">&#x27;IV&#x27;</span>:<span class="number">3</span>, <span class="string">&#x27;V&#x27;</span>:<span class="number">5</span>, <span class="string">&#x27;IX&#x27;</span>:<span class="number">8</span>, <span class="string">&#x27;X&#x27;</span>:<span class="number">10</span>, <span class="string">&#x27;XL&#x27;</span>:<span class="number">30</span>, <span class="string">&#x27;L&#x27;</span>:<span class="number">50</span>, <span class="string">&#x27;XC&#x27;</span>:<span class="number">80</span>, <span class="string">&#x27;C&#x27;</span>:<span class="number">100</span>, <span class="string">&#x27;CD&#x27;</span>:<span class="number">300</span>, <span class="string">&#x27;D&#x27;</span>:<span class="number">500</span>, <span class="string">&#x27;CM&#x27;</span>:<span class="number">800</span>, <span class="string">&#x27;M&#x27;</span>:<span class="number">1000</span>&#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sum</span>(d.get(s[<span class="built_in">max</span>(i-<span class="number">1</span>, <span class="number">0</span>):i+<span class="number">1</span>], d[n]) <span class="keyword">for</span> i, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(s))</span><br></pre></td></tr></table></figure>
<ul>
<li>构建一个字典记录所有罗马数字子串，注意长度为2的子串记录的值是（实际值-子串内左边罗马数字代表的数值）</li>
<li>这样一来，遍历整个s的时候判断当前位置和前一个位置的两个字符组成的字符串是否在字典内，如果在就记录值，不在就说明当前位置不存在小数字在前面的情况，直接记录当前位置字符对应值</li>
<li>举个例子，遍历经过IV的时候先记录I的对应值1再往前移动一步记录IV的值3，加起来正好是IV的真实值4。max函数在这里是为了防止遍历第一个字符的时候出现[-1:0]的情况<h2 id="14-Longest-Common-Prefix-2行"><a href="#14-Longest-Common-Prefix-2行" class="headerlink" title="14. Longest Common Prefix 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/longest-common-prefix/">14. Longest Common Prefix 2行</a></h2></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">longestCommonPrefix</span>(<span class="params">self, strs: <span class="type">List</span>[<span class="built_in">str</span>]</span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        r = [<span class="built_in">len</span>(<span class="built_in">set</span>(c)) == <span class="number">1</span> <span class="keyword">for</span> c <span class="keyword">in</span> <span class="built_in">zip</span>(*strs)] + [<span class="number">0</span>]</span><br><span class="line">        <span class="keyword">return</span> strs[<span class="number">0</span>][:r.index(<span class="number">0</span>)] <span class="keyword">if</span> strs <span class="keyword">else</span> <span class="string">&#x27;&#x27;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>利用好zip和set</li>
<li>os 模块有提供一样的函数  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">longestCommonPrefix</span>(<span class="params">self, strs: <span class="type">List</span>[<span class="built_in">str</span>]</span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">	<span class="keyword">return</span> os.path.commonprefix(strs)</span><br></pre></td></tr></table></figure>
<h2 id="15-3Sum-5行"><a href="#15-3Sum-5行" class="headerlink" title="15. 3Sum 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/3sum/">15. 3Sum 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">threeSum</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        nums, r = <span class="built_in">sorted</span>(nums), <span class="built_in">set</span>()</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> [i <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(nums)-<span class="number">2</span>) <span class="keyword">if</span> i &lt; <span class="number">1</span> <span class="keyword">or</span> nums[i] &gt; nums[i-<span class="number">1</span>]]:</span><br><span class="line">            d = &#123;-nums[i]-n: j <span class="keyword">for</span> j, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(nums[i + <span class="number">1</span>:])&#125;</span><br><span class="line">            r.update([(nums[i], n, -nums[i]-n) <span class="keyword">for</span> j, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(nums[i+<span class="number">1</span>:]) <span class="keyword">if</span> n <span class="keyword">in</span> d <span class="keyword">and</span> d[n] &gt; j])</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="built_in">list</span>, r))</span><br></pre></td></tr></table></figure></li>
<li>时间复杂度：$O(N^2)$</li>
<li>这里 sort 一是为了避免重复，这一点可以体现在我们输出的结果都是升序的，如果不这么做 set 无法排除一些相同结果，而是为了节省计算，防止超时</li>
<li>for 循环内部的代码思想同<code>第一题 Two Sum</code>，用字典记录｛需要的值:当前索引｝，如果字典中存在相同的数字，那么将会记录比较大的那个索引，因此可以用<code>d[n] &gt; i</code>来避免一个元素重复选择</li>
<li><code>(nums[i], n, -nums[i]-n)</code>保证了列表升序<h2 id="16-3Sum-Closest-7行"><a href="#16-3Sum-Closest-7行" class="headerlink" title="16. 3Sum Closest 7行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/3sum-closest/">16. 3Sum Closest 7行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">threeSumClosest</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], target: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        nums, r, end = <span class="built_in">sorted</span>(nums), <span class="built_in">float</span>(<span class="string">&#x27;inf&#x27;</span>), <span class="built_in">len</span>(nums) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">for</span> c <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(nums) - <span class="number">2</span>):</span><br><span class="line">            i, j = <span class="built_in">max</span>(c + <span class="number">1</span>, bisect.bisect_left(nums, target - nums[end] - nums[c], c + <span class="number">1</span>, end) - <span class="number">1</span>), end</span><br><span class="line">            <span class="keyword">while</span> r != target <span class="keyword">and</span> i &lt; j:</span><br><span class="line">                s = nums[c] + nums[i] + nums[j]</span><br><span class="line">                r, i, j = <span class="built_in">min</span>(r, s, key=<span class="keyword">lambda</span> x: <span class="built_in">abs</span>(x - target)), i + (s &lt; target), j - (s &gt; target)</span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li><code>float(&#39;inf&#39;) = ＋∞(正无穷)</code></li>
<li>排序，遍历，双指针，$O(N^2)$ 时间复杂度，二分法初始化</li>
<li>排序是为了使用双指针，首先遍历得到索引 c，然后计算 c，左指针 i，右指针 j 对应数字之和，如果大于 target，j 向内移动，否则 i 向内移动</li>
<li>i 的初始值不是 c + 1，是为了减少计算量，用二分法得到一个合理的初始值<h2 id="17-Letter-Combinations-of-a-Phone-Number-3行"><a href="#17-Letter-Combinations-of-a-Phone-Number-3行" class="headerlink" title="17. Letter Combinations of a Phone Number 3行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/letter-combinations-of-a-phone-number/">17. Letter Combinations of a Phone Number 3行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">letterCombinations</span>(<span class="params">self, digits: <span class="built_in">str</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">str</span>]:</span><br><span class="line">        <span class="keyword">from</span> itertools <span class="keyword">import</span> product</span><br><span class="line">        l = <span class="string">&#x27;- - abc def ghi jkl mno pqrs tuv wxyz&#x27;</span>.split()</span><br><span class="line">        <span class="keyword">return</span> [<span class="string">&#x27;&#x27;</span>.join(c) <span class="keyword">for</span> c <span class="keyword">in</span> product(*[l[<span class="built_in">int</span>(i)] <span class="keyword">for</span> i <span class="keyword">in</span> digits])] <span class="keyword">if</span> digits <span class="keyword">else</span> []</span><br></pre></td></tr></table></figure></li>
<li>本题相当于求解笛卡尔积<h2 id="18-4Sum-5行"><a href="#18-4Sum-5行" class="headerlink" title="18. 4Sum 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/4sum/">18. 4Sum 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">fourSum</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], target: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        <span class="keyword">from</span> itertools <span class="keyword">import</span> combinations <span class="keyword">as</span> com</span><br><span class="line">        dic, l = collections.defaultdict(<span class="built_in">list</span>), [*com(<span class="built_in">range</span>(<span class="built_in">len</span>(nums)), <span class="number">2</span>)]</span><br><span class="line">        <span class="keyword">for</span> a, b <span class="keyword">in</span> l: dic[target - nums[a] - nums[b]].append((a, b))</span><br><span class="line">        r = [(*ab, c, d) <span class="keyword">for</span> c, d <span class="keyword">in</span> l <span class="keyword">for</span> ab <span class="keyword">in</span> dic[nums[c] + nums[d]]]</span><br><span class="line">        <span class="keyword">return</span> [*<span class="built_in">set</span>(<span class="built_in">tuple</span>(<span class="built_in">sorted</span>(nums[i] <span class="keyword">for</span> i <span class="keyword">in</span> t)) <span class="keyword">for</span> t <span class="keyword">in</span> r <span class="keyword">if</span> <span class="built_in">len</span>(<span class="built_in">set</span>(t)) == <span class="number">4</span>)]</span><br></pre></td></tr></table></figure></li>
<li>思想类似于 2SUM，先得到任意两个数字的和记入字典，然后再获得其余任意俩个数字，看看是否匹配。2个 2SUM 相当于 4SUM。时间复杂度为 $O(N^2)$</li>
<li>1.用 combination 获得 nums 中任意两个不同索引的组合</li>
<li>2.用字典记录任意两个数字的和，dic =｛除了这两个数字之外还差多少：这俩个数字在 nums 中的索引｝</li>
<li>3.用 r 记录所有满足条件的索引序列，注意此时可能含有重复的索引</li>
<li>4.利用 len + set 保证 a，b，c，d 各不相等，用 set 删除重复的结果<h2 id="19-Remove-Nth-Node-From-End-of-List-5行"><a href="#19-Remove-Nth-Node-From-End-of-List-5行" class="headerlink" title="19. Remove Nth Node From End of List 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/remove-nth-node-from-end-of-list/">19. Remove Nth Node From End of List 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">removeNthFromEnd</span>(<span class="params">self, head: ListNode, n: <span class="built_in">int</span></span>) -&gt; ListNode:</span><br><span class="line">        l = []</span><br><span class="line">        <span class="keyword">while</span> head: l, head = l + [head], head.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">if</span> n != <span class="built_in">len</span>(l): l[-n-<span class="number">1</span>].<span class="built_in">next</span> = l[-n].<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">del</span> l[-n]</span><br><span class="line">        <span class="keyword">return</span> l <span class="keyword">and</span> l[<span class="number">0</span>]</span><br></pre></td></tr></table></figure></li>
<li>列表记录整个链表，换成队列记录最后几个可以把空间复杂度压到 $O(1)$<h2 id="20-Valid-Parentheses-2行"><a href="#20-Valid-Parentheses-2行" class="headerlink" title="20. Valid Parentheses 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/valid-parentheses/">20. Valid Parentheses 2行</a></h2></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isValid</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">while</span> <span class="built_in">any</span>((<span class="string">&#x27;()&#x27;</span> <span class="keyword">in</span> s, <span class="string">&#x27;[]&#x27;</span> <span class="keyword">in</span> s, <span class="string">&#x27;&#123;&#125;&#x27;</span> <span class="keyword">in</span> s)): s = s.replace(<span class="string">&#x27;()&#x27;</span>, <span class="string">&#x27;&#x27;</span>).replace(<span class="string">&#x27;[]&#x27;</span>, <span class="string">&#x27;&#x27;</span>).replace(<span class="string">&#x27;&#123;&#125;&#x27;</span>, <span class="string">&#x27;&#x27;</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">not</span> s</span><br></pre></td></tr></table></figure>
<ul>
<li><p>不断删除有效括号直到不能删除，思路简单效率低。另外，stack的方法也很简单，而且快多了。</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isValid</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        stack, d = [], &#123;<span class="string">&#x27;&#123;&#x27;</span>: <span class="string">&#x27;&#125;&#x27;</span>, <span class="string">&#x27;[&#x27;</span>: <span class="string">&#x27;]&#x27;</span>, <span class="string">&#x27;(&#x27;</span>: <span class="string">&#x27;)&#x27;</span>&#125;</span><br><span class="line">        <span class="keyword">for</span> p <span class="keyword">in</span> s:</span><br><span class="line">            <span class="keyword">if</span> p <span class="keyword">in</span> <span class="string">&#x27;&#123;[(&#x27;</span>:</span><br><span class="line">                stack += [p];</span><br><span class="line">            <span class="keyword">elif</span> <span class="keyword">not</span> (stack <span class="keyword">and</span> d[stack.pop()] == p):</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">not</span> stack</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="21-Merge-Two-Sorted-Lists-4行"><a href="#21-Merge-Two-Sorted-Lists-4行" class="headerlink" title="21. Merge Two Sorted Lists 4行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/merge-two-sorted-lists/">21. Merge Two Sorted Lists 4行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">mergeTwoLists</span>(<span class="params">self, l1: ListNode, l2: ListNode</span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">if</span> l1 <span class="keyword">and</span> l2:</span><br><span class="line">            <span class="keyword">if</span> l1.val &gt; l2.val: l1, l2 = l2, l1</span><br><span class="line">            l1.<span class="built_in">next</span> = self.mergeTwoLists(l1.<span class="built_in">next</span>, l2)</span><br><span class="line">        <span class="keyword">return</span> l1 <span class="keyword">or</span> l2</span><br></pre></td></tr></table></figure>
<ul>
<li><code>7 or 9</code> 等于 7</li>
<li><code>None and 7</code> 等于 None<h2 id="23-Merge-k-Sorted-Lists-4行"><a href="#23-Merge-k-Sorted-Lists-4行" class="headerlink" title="23. Merge k Sorted Lists 4行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/merge-k-sorted-lists/">23. Merge k Sorted Lists 4行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">mergeKLists</span>(<span class="params">self, lists: <span class="type">List</span>[ListNode]</span>) -&gt; ListNode:</span><br><span class="line">        r, n, p = [], lists <span class="keyword">and</span> lists.pop(), <span class="literal">None</span></span><br><span class="line">        <span class="keyword">while</span> lists <span class="keyword">or</span> n: r[<span class="built_in">len</span>(r):], n = ([n], n.<span class="built_in">next</span> <span class="keyword">or</span> lists <span class="keyword">and</span> lists.pop()) <span class="keyword">if</span> n <span class="keyword">else</span> ([], lists.pop())</span><br><span class="line">        <span class="keyword">for</span> n <span class="keyword">in</span> <span class="built_in">sorted</span>(r, key=<span class="keyword">lambda</span> x: x.val, reverse=<span class="literal">True</span>): n.<span class="built_in">next</span>, p = p, n</span><br><span class="line">        <span class="keyword">return</span> n <span class="keyword">if</span> r <span class="keyword">else</span> []</span><br></pre></td></tr></table></figure></li>
<li><p>本题思路：</p>
<ol>
<li>把题目给的所有链表中的所有节点放进一个列表 r。</li>
<li>对这个列表 r 中的所有节点进行从大到小的排序。$O(N\log N)$</li>
<li>把每个节点的指针指向前一个节点。（第一个节点，也就是最大的那个，指向None。）</li>
<li>返回最后一个节点，也就是整个新链表的开头。</li>
</ol>
</li>
<li><p>如何把所有节点放进 r(result link)？</p>
<p>  我们首先初始化 r 为空列表，初始化 n(node) 为题目所给的第一个链表的开头节点，并删除lists中的这个节点，接着进入while循环，如果 n 不为空，那么 <code>r += [n]</code>，这里使用了切片的技巧（<code>r[len(r):]=[n]</code>相当于<code>r=r+[n]</code>），<code>n=n.next</code>，如果n是第一个链表的最后一个节点的话n.next就是None，下一次while的时候如果lists不为空就说明还有别的链表，此时n为None，我们让 r 不变，<code>n=lists.pop()</code>，也就是从lists中再取下一个节点赋值给n，重复以上步骤直到 lists 为空，我们就把所有节点放进 r 了。</p>
</li>
<li><p>怎么对 r 排序？</p>
<p>  用了sorted函数，其中key定义了排序时用来比较的是每个元素的val属性，同时设置reverse为True代表降序排序。</p>
</li>
<li><p>如何修改每个节点的指针？</p>
<p>  我们初始化 p(previous node) 为None。遍历降序排好的列表 r，r中的第一个元素就是值最大的元素，也就是我们应该返回的链表的结尾，我们设置它指向None，然后让p=这个节点，继续for循环。之后每经过一个节点 n 就把这个节点的next属性设置为上一个节点 p，遍历完成之后的 n，也就是我们遍历经过的最后一个元素，拥有最小的值，自然就是整个新链表的起始节点，我们将其作为输出值，函数返回。</p>
<h2 id="24-Swap-Nodes-in-Pairs-3行"><a href="#24-Swap-Nodes-in-Pairs-3行" class="headerlink" title="24. Swap Nodes in Pairs 3行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/swap-nodes-in-pairs/">24. Swap Nodes in Pairs 3行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">swapPairs</span>(<span class="params">self, head: ListNode</span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">if</span> head <span class="keyword">and</span> head.<span class="built_in">next</span>:</span><br><span class="line">            head.<span class="built_in">next</span>.<span class="built_in">next</span>, head.<span class="built_in">next</span>, head = head, self.swapPairs(head.<span class="built_in">next</span>.<span class="built_in">next</span>), head.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">return</span> head</span><br></pre></td></tr></table></figure></li>
<li>每次递归交换两个节点，并返回新头参与上次递归</li>
<li>多值交换参考<a href="#常用技巧总结"><code>这里</code></a><h2 id="26-Remove-Duplicates-from-Sorted-Array-3行"><a href="#26-Remove-Duplicates-from-Sorted-Array-3行" class="headerlink" title="26. Remove Duplicates from Sorted Array 3行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/remove-duplicates-from-sorted-array/">26. Remove Duplicates from Sorted Array 3行</a></h2></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">removeDuplicates</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(nums)-<span class="number">1</span>, <span class="number">0</span>, -<span class="number">1</span>):</span><br><span class="line">            <span class="keyword">if</span> nums[i] == nums[i-<span class="number">1</span>]: nums.pop(i)</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">len</span>(nums)</span><br></pre></td></tr></table></figure>
<ul>
<li>时间效率$O(N^2)$, pop操作的平均时间复杂度为$O(N)$, 空间效率$O(1)$，逆遍历可以防止删除某个元素后影响下一步索引的定位</li>
<li>每次删除数组元素会引发大量的数据迁移操作，使用以下算法解题效率更高  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">removeDuplicates</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">	i = <span class="number">0</span></span><br><span class="line">	<span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, <span class="built_in">len</span>(nums)):</span><br><span class="line">	    <span class="keyword">if</span> nums[j] != nums[i]:</span><br><span class="line">		nums[i + <span class="number">1</span>] = nums[j]</span><br><span class="line">		i += <span class="number">1</span></span><br><span class="line">	<span class="keyword">return</span> i + <span class="number">1</span> <span class="keyword">if</span> nums <span class="keyword">else</span> <span class="number">0</span></span><br></pre></td></tr></table></figure>
<ul>
<li>此解法思路同官方题解</li>
<li>数组完成排序后，我们可以放置两个指针 i 和 j，其中 i 是慢指针，而 j 是快指针。只要 nums[i] = nums[j]，我们就增加 j 以跳过重复项。当我们遇到 nums[j] != nums[i]时，跳过重复项的运行已经结束，因此我们必须把它（nums[j]）的值复制到 nums[i + 1]。然后递增 i，接着我们将再次重复相同的过程，直到 j 到达数组的末尾为止<h2 id="28-Implement-strStr-1行"><a href="#28-Implement-strStr-1行" class="headerlink" title="28. Implement strStr() 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/implement-strstr/">28. Implement strStr() 1行</a></h2></li>
</ul>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">strStr</span>(<span class="params">self, haystack: <span class="built_in">str</span>, needle: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">		<span class="keyword">return</span> haystack.find(needle)</span><br></pre></td></tr></table></figure>
<ul>
<li><p>不用内置函数也可以</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">	<span class="keyword">def</span> <span class="title function_">strStr</span>(<span class="params">self, haystack: <span class="string">&#x27;str&#x27;</span>, needle: <span class="string">&#x27;str&#x27;</span></span>) -&gt; <span class="string">&#x27;int&#x27;</span>:</span><br><span class="line">	    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">0</span>, <span class="built_in">len</span>(haystack) - <span class="built_in">len</span>(needle) + <span class="number">1</span>):</span><br><span class="line">	        <span class="keyword">if</span> haystack[i:i+<span class="built_in">len</span>(needle)] == needle:</span><br><span class="line">	            <span class="keyword">return</span> i</span><br><span class="line">    	<span class="keyword">return</span> -<span class="number">1</span></span><br></pre></td></tr></table></figure>
<h2 id="29-Divide-Two-Integers-5行"><a href="#29-Divide-Two-Integers-5行" class="headerlink" title="29. Divide Two Integers 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/divide-two-integers/">29. Divide Two Integers 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">divide</span>(<span class="params">self, dividend: <span class="built_in">int</span>, divisor: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        a, b, r, t = <span class="built_in">abs</span>(dividend), <span class="built_in">abs</span>(divisor), <span class="number">0</span>, <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> a &gt;= b <span class="keyword">or</span> t &gt; <span class="number">1</span>:</span><br><span class="line">            <span class="keyword">if</span> a &gt;= b: r += t; a -= b; t += t; b += b</span><br><span class="line">            <span class="keyword">else</span>: t &gt;&gt;= <span class="number">1</span>; b &gt;&gt;= <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">min</span>((-r, r)[dividend ^ divisor &gt;= <span class="number">0</span>], (<span class="number">1</span> &lt;&lt; <span class="number">31</span>) - <span class="number">1</span>)</span><br></pre></td></tr></table></figure></li>
<li>让被除数不断减去除数，直到不够减。每次减完后除数翻倍，并记录当前为初始除数的几倍（用 t 表示倍数 time），若发现不够减且 t 不为 1 则让除数变为原来的一半， t 也减半</li>
<li>a 为被除数绝对值，b 为除数绝对值，r 表示 result，t 表示当前除数对于原始除数的倍数</li>
<li>a &lt;&lt; b 相当于 <code>a * 2**b</code>，a &gt;&gt; b 相当于 <code>a // 2**b</code></li>
<li>异或操作 ^ 可以判断俩数字是否异号<h2 id="33-Search-in-Rotated-Sorted-Array-3行"><a href="#33-Search-in-Rotated-Sorted-Array-3行" class="headerlink" title="33. Search in Rotated Sorted Array 3行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/search-in-rotated-sorted-array/">33. Search in Rotated Sorted Array 3行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">search</span>(<span class="params">self, nums, target</span>):</span><br><span class="line">        self.__class__.__getitem__ = <span class="keyword">lambda</span> self, m: <span class="keyword">not</span>(target &lt; nums[<span class="number">0</span>] &lt;= nums[m] <span class="keyword">or</span> nums[<span class="number">0</span>] &lt;= nums[m] &lt; target <span class="keyword">or</span> nums[m] &lt; target &lt;= nums[-<span class="number">1</span>])</span><br><span class="line">        i = bisect.bisect_left(self, <span class="literal">True</span>, <span class="number">0</span>, <span class="built_in">len</span>(nums))</span><br><span class="line">        <span class="keyword">return</span> i <span class="keyword">if</span> target <span class="keyword">in</span> nums[i:i+<span class="number">1</span>] <span class="keyword">else</span> -<span class="number">1</span></span><br></pre></td></tr></table></figure></li>
<li>作出数列的函数图像，可以看作是一个含断点的局部递增函数，形如:zap:，前面一段总是比较高</li>
<li>python 中 bisect 模块针对的是 list, 如果直接构造 list，相当于遍历所有元素，时间复杂度为 $O(N)$ 而不是 $O(logN)$，因此我们修改当前类的魔法方法伪造 list，然后用当前类代替list</li>
<li>用二分搜索时，m 代表 middle，low 代表 low，hi 代表 high，当满足任一条件｛① targe &lt; middle 且 middle 在前一段上 且 target &lt; nums[0] ② target &gt; middle 且 middle 在第一段上 ③ target &gt; middle 且 middle 在第二段上 且 target &lt;= nums[-1]｝时，应该向右搜索，因此 getitem 返回 False。</li>
<li>另外还有一种简单的思路：二分法找到断点的位置恢复原始数组，然后正常二分法即可  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">search</span>(<span class="params">self, nums, target</span>):</span><br><span class="line">	lo, hi, k = <span class="number">0</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span>, -<span class="number">1</span></span><br><span class="line">	<span class="keyword">while</span> lo &lt;= hi:</span><br><span class="line">	    m = (lo + hi) // <span class="number">2</span></span><br><span class="line">	    <span class="keyword">if</span> m == <span class="built_in">len</span>(nums) - <span class="number">1</span> <span class="keyword">or</span> nums[m] &gt; nums[m+<span class="number">1</span>]:</span><br><span class="line">		k = m + <span class="number">1</span></span><br><span class="line">		<span class="keyword">break</span></span><br><span class="line">	    <span class="keyword">elif</span> m == <span class="number">0</span> <span class="keyword">or</span> nums[m] &lt; nums[m-<span class="number">1</span>]:</span><br><span class="line">		k = m</span><br><span class="line">		<span class="keyword">break</span></span><br><span class="line">	    <span class="keyword">if</span> nums[m] &gt; nums[<span class="number">0</span>]:</span><br><span class="line">		lo = m + <span class="number">1</span></span><br><span class="line">	    <span class="keyword">else</span>:</span><br><span class="line">		hi = m - <span class="number">1</span></span><br><span class="line">	i = (bisect.bisect_left(nums[k:] + nums[:k], target) + k) % <span class="built_in">max</span>(<span class="built_in">len</span>(nums), <span class="number">1</span>)</span><br><span class="line">	<span class="keyword">return</span> i <span class="keyword">if</span> nums <span class="keyword">and</span> nums[i] == target <span class="keyword">else</span> -<span class="number">1</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="34-在排序数组中查找元素的第一个和最后一个位置"><a href="#34-在排序数组中查找元素的第一个和最后一个位置" class="headerlink" title="34. 在排序数组中查找元素的第一个和最后一个位置"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/">34. 在排序数组中查找元素的第一个和最后一个位置</a></h2><ul>
<li>用自带的bisect函数，一行</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">class Solution:</span><br><span class="line">    def searchRange(self, nums: List[int], target: int) -&gt; List[int]:</span><br><span class="line">        # if not nums or target not in nums:  return [-1, -1]</span><br><span class="line">        return [bisect.bisect_left(nums, target), bisect.bisect_right(nums, target)-1] \</span><br><span class="line">            if nums and target in nums else [-1, -1]</span><br></pre></td></tr></table></figure>
<h2 id="35-Search-Insert-Position-1行"><a href="#35-Search-Insert-Position-1行" class="headerlink" title="35. Search Insert Position 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problemset/all/?search=35">35. Search Insert Position 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">searchInsert</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], target: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> bisect.bisect_left(nums, target, <span class="number">0</span>, <span class="built_in">len</span>(nums))</span><br></pre></td></tr></table></figure>
<h2 id="36-Valid-Sudoku-4行"><a href="#36-Valid-Sudoku-4行" class="headerlink" title="36. Valid Sudoku 4行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/valid-sudoku/">36. Valid Sudoku 4行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isValidSudoku</span>(<span class="params">self, board: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">str</span>]]</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        row = [[x <span class="keyword">for</span> x <span class="keyword">in</span> y <span class="keyword">if</span> x != <span class="string">&#x27;.&#x27;</span>] <span class="keyword">for</span> y <span class="keyword">in</span> board]</span><br><span class="line">        col = [[x <span class="keyword">for</span> x <span class="keyword">in</span> y <span class="keyword">if</span> x != <span class="string">&#x27;.&#x27;</span>] <span class="keyword">for</span> y <span class="keyword">in</span> <span class="built_in">zip</span>(*board)]</span><br><span class="line">        pal = [[board[i+m][j+n] <span class="keyword">for</span> m <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">3</span>) <span class="keyword">for</span> n <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">3</span>) <span class="keyword">if</span> board[i+m][j+n] != <span class="string">&#x27;.&#x27;</span>] <span class="keyword">for</span> i <span class="keyword">in</span> (<span class="number">0</span>, <span class="number">3</span>, <span class="number">6</span>) <span class="keyword">for</span> j <span class="keyword">in</span> (<span class="number">0</span>, <span class="number">3</span>, <span class="number">6</span>)]</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">all</span>(<span class="built_in">len</span>(<span class="built_in">set</span>(x)) == <span class="built_in">len</span>(x) <span class="keyword">for</span> x <span class="keyword">in</span> (*row, *col, *pal))</span><br></pre></td></tr></table></figure>
<ul>
<li>利用 set 检查每个区块中是否有重复数字</li>
<li>pal 取区块的遍历方式是利用 i，j 遍历每个宫格左上角位置，然后取 3*3 区块<h2 id="38-Count-and-Say-1行"><a href="#38-Count-and-Say-1行" class="headerlink" title="38. Count and Say 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/count-and-say/">38. Count and Say 1行</a></h2></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">countAndSay</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;1&#x27;</span> * (n <span class="keyword">is</span> <span class="number">1</span>) <span class="keyword">or</span> re.sub(<span class="string">r&#x27;(.)\1*&#x27;</span>, <span class="keyword">lambda</span> m: <span class="built_in">str</span>(<span class="built_in">len</span>(m.group())) + m.group(<span class="number">1</span>), self.countAndSay(n - <span class="number">1</span>))</span><br></pre></td></tr></table></figure>
<ul>
<li>正则表达式 re.sub(正则，替换字符串或函数，被替换字符串，是否区分大小写)</li>
<li>. 可匹配任意一个除了\n的字符<br>(.) 匹配任意一个除了\n的字符并把这个匹配结果放进第一组<br>(.)\1 匹配一个任意字符的二次重复并把那个字符放入数组<br>(.)\1* 匹配一个任意字符的多次重复并把那个字符放入数组</li>
<li>group(default=0)可以取匹配文本   group(1)取第一个括号内的文本<h2 id="43-Multiply-Strings-5行"><a href="#43-Multiply-Strings-5行" class="headerlink" title="43. Multiply Strings 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/multiply-strings/">43. Multiply Strings 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">multiply</span>(<span class="params">self, num1: <span class="built_in">str</span>, num2: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        d = &#123;&#125;</span><br><span class="line">        <span class="keyword">for</span> i, n1 <span class="keyword">in</span> <span class="built_in">enumerate</span>(num1[::-<span class="number">1</span>]):</span><br><span class="line">            <span class="keyword">for</span> j, n2 <span class="keyword">in</span> <span class="built_in">enumerate</span>(num2[::-<span class="number">1</span>]): d[i + j] = d.get(i + j, <span class="number">0</span>) + <span class="built_in">int</span>(n1) * <span class="built_in">int</span>(n2)</span><br><span class="line">        <span class="keyword">for</span> k <span class="keyword">in</span> [*d]: d[k + <span class="number">1</span>], d[k] = d.get(k + <span class="number">1</span>, <span class="number">0</span>) + <span class="built_in">int</span>(d[k] * <span class="number">0.1</span>), d[k] % <span class="number">10</span></span><br><span class="line">        <span class="keyword">return</span> re.sub(<span class="string">&#x27;^0*&#x27;</span>, <span class="string">&#x27;&#x27;</span>, <span class="string">&#x27;&#x27;</span>.join(<span class="built_in">map</span>(<span class="built_in">str</span>, d.values()))[::-<span class="number">1</span>]) <span class="keyword">or</span> <span class="string">&#x27;0&#x27;</span></span><br></pre></td></tr></table></figure></li>
<li>本题的难点在于计算整数的时候不能超过32bits，因此使用竖式计算</li>
<li>我们遍历num1中的每个数字n1，然后带着这个数字遍历num2中的每个数字n2做乘法，所得乘积放进 d 中相应的位置然后逐位计算结果</li>
<li>i + j 正好对应俩个数字相乘后所在的位置，比如 0 + 0 就应该是个位， 0 + 1 就是十位， 1 + 1 百位。这里所说的位置可以参考<a target="_blank" rel="noopener" href="https://blog.csdn.net/Give_me_the_who/article/details/80313860">这篇博客中的过程图</a></li>
<li>若完全不想使用int()可以参考：  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">multiply</span>(<span class="params">self, num1: <span class="built_in">str</span>, num2: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">	d = &#123;&#125;</span><br><span class="line">	<span class="keyword">for</span> i, n1 <span class="keyword">in</span> <span class="built_in">enumerate</span>(num1[::-<span class="number">1</span>]):</span><br><span class="line">	    <span class="keyword">for</span> j, n2 <span class="keyword">in</span> <span class="built_in">enumerate</span>(num2[::-<span class="number">1</span>]):</span><br><span class="line">		d[i + j] = d.get(i + j, <span class="number">0</span>) + (<span class="built_in">ord</span>(n1) - <span class="number">48</span>) * (<span class="built_in">ord</span>(n2) - <span class="number">48</span>)</span><br><span class="line">	<span class="keyword">for</span> k <span class="keyword">in</span> [*d]:</span><br><span class="line">	    d[k + <span class="number">1</span>], d[k] = d.get(k + <span class="number">1</span>, <span class="number">0</span>) + math.floor(d[k] * <span class="number">0.1</span>), d[k] % <span class="number">10</span></span><br><span class="line">	<span class="keyword">return</span> re.sub(<span class="string">&#x27;^0*&#x27;</span>, <span class="string">&#x27;&#x27;</span>, <span class="string">&#x27;&#x27;</span>.join(<span class="built_in">map</span>(<span class="built_in">str</span>, d.values()))[::-<span class="number">1</span>]) <span class="keyword">or</span> <span class="string">&#x27;0&#x27;</span></span><br></pre></td></tr></table></figure>
<h2 id="46-Permutations-1行"><a href="#46-Permutations-1行" class="headerlink" title="46. Permutations 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/permutations/">46. Permutations 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">permute</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        <span class="keyword">return</span> [[n] + sub <span class="keyword">for</span> i, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(nums) <span class="keyword">for</span> sub <span class="keyword">in</span> self.permute(nums[:i] + nums[i+<span class="number">1</span>:])] <span class="keyword">or</span> [nums]</span><br></pre></td></tr></table></figure></li>
<li>每次固定第一个数字递归地排列数组剩余部分</li>
<li><p>python 有内置函数可以直接实现</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">permute</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">	<span class="keyword">from</span> itertools <span class="keyword">import</span> permutations</span><br><span class="line">	<span class="keyword">return</span> <span class="built_in">list</span>(permutations(nums))</span><br></pre></td></tr></table></figure>
<h2 id="49-Group-Anagrams-1行"><a href="#49-Group-Anagrams-1行" class="headerlink" title="49. Group Anagrams 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/group-anagrams/">49. Group Anagrams 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">groupAnagrams</span>(<span class="params">self, strs</span>):</span><br><span class="line">        <span class="keyword">return</span> [[*x] <span class="keyword">for</span> _, x <span class="keyword">in</span> itertools.groupby(<span class="built_in">sorted</span>(strs, key=<span class="built_in">sorted</span>), <span class="built_in">sorted</span>)]</span><br></pre></td></tr></table></figure></li>
<li>使用 groupby 函数依据 sorted 结果分组<h2 id="50-Pow-x-n-2行"><a href="#50-Pow-x-n-2行" class="headerlink" title="50. Pow(x, n) 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/powx-n/">50. Pow(x, n) 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">myPow</span>(<span class="params">self, x, n, r=<span class="number">1</span></span>) -&gt; <span class="built_in">float</span>:</span><br><span class="line">        x, n = n &lt; <span class="number">0</span> <span class="keyword">and</span> <span class="number">1</span> / x <span class="keyword">or</span> x, <span class="built_in">abs</span>(n)</span><br><span class="line">        <span class="keyword">return</span> self.myPow(x * x, n // <span class="number">2</span>, r * (<span class="keyword">not</span> n % <span class="number">2</span> <span class="keyword">or</span> x)) <span class="keyword">if</span> n <span class="keyword">else</span> r</span><br></pre></td></tr></table></figure></li>
<li>尾递归 $O(\log N)$ 解法</li>
<li><code>x^4</code> 正常计算过程：<code>x * x * x * x</code>，$O(N)$</li>
<li>优化后：<code>(x**2)**2</code>，$O(\log N)$<h2 id="53-Maximum-Subarray-2行"><a href="#53-Maximum-Subarray-2行" class="headerlink" title="53. Maximum Subarray 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/maximum-subarray/">53. Maximum Subarray 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">maxSubArray</span>(<span class="params">self, nums</span>):</span><br><span class="line">        <span class="keyword">from</span> functools <span class="keyword">import</span> reduce</span><br><span class="line">        <span class="keyword">return</span> reduce(<span class="keyword">lambda</span> r, x: (<span class="built_in">max</span>(r[<span class="number">0</span>], r[<span class="number">1</span>]+x), <span class="built_in">max</span>(r[<span class="number">1</span>]+x,x)), nums, (<span class="built_in">max</span>(nums), <span class="number">0</span>))[<span class="number">0</span>]</span><br></pre></td></tr></table></figure></li>
<li><a target="_blank" rel="noopener" href="https://www.cnblogs.com/XXCXY/p/5180245.html">reduce 函数详解</a></li>
<li>r[0]代表以当前位置为结尾的局部最优解</li>
<li>r[1]代表全局最优解</li>
<li><p>直接DP的解法更好理解一些</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">maxSubArray</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, <span class="built_in">len</span>(nums)):</span><br><span class="line">            nums[i] = <span class="built_in">max</span>(nums[i], nums[i] + nums[i-<span class="number">1</span>])</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">max</span>(nums)</span><br></pre></td></tr></table></figure>
<h2 id="54-Spiral-Matrix-1行"><a href="#54-Spiral-Matrix-1行" class="headerlink" title="54. Spiral Matrix 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/spiral-matrix/">54. Spiral Matrix 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">spiralOrder</span>(<span class="params">self, matrix: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> matrix <span class="keyword">and</span> [*matrix.pop(<span class="number">0</span>)] + self.spiralOrder([*<span class="built_in">zip</span>(*matrix)][::-<span class="number">1</span>])</span><br></pre></td></tr></table></figure></li>
<li>为什么是<code>[*matrix.pop(0)]</code>而不是<code>matrix.pop(0)</code>？因为对于后面的递归，传进来的列表中元素是tuple<h2 id="58-Length-of-Last-Word-1行"><a href="#58-Length-of-Last-Word-1行" class="headerlink" title="58. Length of Last Word 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/length-of-last-word/">58. Length of Last Word 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">lengthOfLastWord</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">len</span>(s.strip(<span class="string">&#x27; &#x27;</span>).split(<span class="string">&#x27; &#x27;</span>)[-<span class="number">1</span>])</span><br></pre></td></tr></table></figure>
<h2 id="59-Spiral-Matrix-II-3行"><a href="#59-Spiral-Matrix-II-3行" class="headerlink" title="59. Spiral Matrix II 3行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/spiral-matrix-ii/">59. Spiral Matrix II 3行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">generateMatrix</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        r, n = [[n**<span class="number">2</span>]], n**<span class="number">2</span></span><br><span class="line">        <span class="keyword">while</span> n &gt; <span class="number">1</span>: n, r = n - <span class="built_in">len</span>(r), [[*<span class="built_in">range</span>(n - <span class="built_in">len</span>(r), n)]] + [*<span class="built_in">zip</span>(*r[::-<span class="number">1</span>])]</span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>流程图<figure class="highlight gherkin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">||<span class="string">  =&gt;  </span>|<span class="string">9</span>|<span class="string">  =&gt;  </span>|<span class="string">8</span>|<span class="string">      </span>|<span class="string">6 7</span>|<span class="string">      </span>|<span class="string">4 5</span>|<span class="string">      </span>|<span class="string">1 2 3</span>|</span><br><span class="line">		 |<span class="string">9</span>|<span class="string">  =&gt;  </span>|<span class="string">9 8</span>|<span class="string">  =&gt;  </span>|<span class="string">9 6</span>|<span class="string">  =&gt;  </span>|<span class="string">8 9 4</span>|</span><br><span class="line">				     |<span class="string">8 7</span>|<span class="string">      </span>|<span class="string">7 6 5</span>|</span><br></pre></td></tr></table></figure>
<h2 id="61-Rotate-List-4行"><a href="#61-Rotate-List-4行" class="headerlink" title="61. Rotate List 4行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/rotate-list/">61. Rotate List 4行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">rotateRight</span>(<span class="params">self, head: ListNode, k: <span class="built_in">int</span></span>) -&gt; ListNode:</span><br><span class="line">        l = []</span><br><span class="line">        <span class="keyword">while</span> head: l[<span class="built_in">len</span>(l):], head = [head], head.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">if</span> l: l[-<span class="number">1</span>].<span class="built_in">next</span>, l[-<span class="number">1</span> - k % <span class="built_in">len</span>(l)].<span class="built_in">next</span> = l[<span class="number">0</span>], <span class="literal">None</span></span><br><span class="line">        <span class="keyword">return</span> l[- k % <span class="built_in">len</span>(l)] <span class="keyword">if</span> l <span class="keyword">else</span> <span class="literal">None</span></span><br></pre></td></tr></table></figure>
<h2 id="62-Unique-Paths-1行"><a href="#62-Unique-Paths-1行" class="headerlink" title="62. Unique Paths 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/unique-paths/">62. Unique Paths 1行</a></h2></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">uniquePaths</span>(<span class="params">self, m: <span class="built_in">int</span>, n: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">int</span>(math.factorial(m+n-<span class="number">2</span>)/math.factorial(m-<span class="number">1</span>)/math.factorial(n-<span class="number">1</span>))</span><br></pre></td></tr></table></figure>
<ul>
<li>题目可以转换为排列组合问题，解是$\cal C^{\min (m,\; n)}_{ m+n}$，从$m+n$个中选出$m$个下移或$n$个右移。</li>
<li>用DP做也很快，以后自己算 $\cal C_a^b$ 也可以用算这题的DP法代替</li>
<li><code>math.factorial</code> 的速度不亚于DP，可能内部有优化</li>
<li>0的阶乘为1<h2 id="66-Plus-One-1行"><a href="#66-Plus-One-1行" class="headerlink" title="66. Plus One 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/plus-one/">66. Plus One 1行</a></h2></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">plusOne</span>(<span class="params">self, digits: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="built_in">int</span>, <span class="built_in">str</span>(<span class="built_in">int</span>(<span class="string">&#x27;&#x27;</span>.join(<span class="built_in">map</span>(<span class="built_in">str</span>, digits))) + <span class="number">1</span>)))</span><br></pre></td></tr></table></figure>
<h2 id="67-Add-Binary-1行"><a href="#67-Add-Binary-1行" class="headerlink" title="67. Add Binary 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/add-binary/">67. Add Binary 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">addBinary</span>(<span class="params">self, a: <span class="built_in">str</span>, b: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">bin</span>(<span class="built_in">int</span>(a, <span class="number">2</span>) + <span class="built_in">int</span>(b, <span class="number">2</span>))[<span class="number">2</span>:]</span><br></pre></td></tr></table></figure>
<ul>
<li>非内置函数解法：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">addBinary</span>(<span class="params">self, a: <span class="built_in">str</span>, b: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        r, p = <span class="string">&#x27;&#x27;</span>, <span class="number">0</span></span><br><span class="line">        d = <span class="built_in">len</span>(b) - <span class="built_in">len</span>(a)</span><br><span class="line">        a = <span class="string">&#x27;0&#x27;</span> * d + a</span><br><span class="line">        b = <span class="string">&#x27;0&#x27;</span> * -d + b</span><br><span class="line">        <span class="keyword">for</span> i, j <span class="keyword">in</span> <span class="built_in">zip</span>(a[::-<span class="number">1</span>], b[::-<span class="number">1</span>]):</span><br><span class="line">            s = <span class="built_in">int</span>(i) + <span class="built_in">int</span>(j) + p</span><br><span class="line">            r = <span class="built_in">str</span>(s % <span class="number">2</span>) + r</span><br><span class="line">            p = s // <span class="number">2</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;1&#x27;</span> + r <span class="keyword">if</span> p <span class="keyword">else</span> r</span><br></pre></td></tr></table></figure>
<h2 id="69-Sqrt-x-1行"><a href="#69-Sqrt-x-1行" class="headerlink" title="69. Sqrt(x) 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/sqrtx/">69. Sqrt(x) 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">mySqrt</span>(<span class="params">self, x: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">int</span>(x ** <span class="number">0.5</span>)</span><br></pre></td></tr></table></figure>
出题者应该是希望看到下面的答案：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">mySqrt</span>(<span class="params">self, x: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        r = x</span><br><span class="line">        <span class="keyword">while</span> r*r &gt; x:</span><br><span class="line">            r = (r + x/r) // <span class="number">2</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">int</span>(r)</span><br></pre></td></tr></table></figure></li>
<li>基本不等式$\frac {a+b}{2} \ge \sqrt{ab}$ 推导自 $(a-b)^2 \ge 0$，注意 $a&gt;0$ 且 $b&gt;0$。</li>
<li>r 代表 result<h2 id="70-Climbing-Stairs-2行"><a href="#70-Climbing-Stairs-2行" class="headerlink" title="70. Climbing Stairs 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/climbing-stairs/">70. Climbing Stairs 2行</a></h2></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">climbStairs</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">from</span> functools <span class="keyword">import</span> reduce</span><br><span class="line">        <span class="keyword">return</span> reduce(<span class="keyword">lambda</span> r, _: (r[<span class="number">1</span>], <span class="built_in">sum</span>(r)), <span class="built_in">range</span>(n), (<span class="number">1</span>, <span class="number">1</span>))[<span class="number">0</span>]</span><br></pre></td></tr></table></figure>
<ul>
<li>dp递归方程：到达当前楼梯的路径数 = 到达上个楼梯的路径数 + 到达上上个楼梯的路径数</li>
<li>这里用一个元组 r 来储存（当前楼梯路径数，下一层楼梯路径数）</li>
<li>利用 reduce 来代替for循环。<a target="_blank" rel="noopener" href="https://www.cnblogs.com/XXCXY/p/5180245.html">reduce 函数详解</a><h2 id="71-Simplify-Path-4行"><a href="#71-Simplify-Path-4行" class="headerlink" title="71. Simplify Path 4行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/simplify-path/">71. Simplify Path 4行</a></h2><figure class="highlight ruby"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">simplifyPath</span>(<span class="params"><span class="variable language_">self</span>, <span class="symbol">path:</span> str</span>) -&gt; <span class="symbol">str:</span></span><br><span class="line">        r = []</span><br><span class="line">        <span class="keyword">for</span> s <span class="keyword">in</span> path.split(<span class="string">&#x27;/&#x27;</span>):</span><br><span class="line">            r = &#123;<span class="string">&#x27;&#x27;</span><span class="symbol">:r</span>, <span class="string">&#x27;.&#x27;</span><span class="symbol">:r</span>, <span class="string">&#x27;..&#x27;</span><span class="symbol">:r</span>[<span class="symbol">:-</span><span class="number">1</span>]&#125;.get(s, r + [s])</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;/&#x27;</span> + <span class="string">&#x27;/&#x27;</span>.join(r)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="73-矩阵置零-5行"><a href="#73-矩阵置零-5行" class="headerlink" title="73. 矩阵置零  5行"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/set-matrix-zeroes/">73. 矩阵置零  5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">setZeroes</span>(<span class="params">self, matrix: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]</span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        row = [[<span class="number">0</span>] * <span class="built_in">len</span>(i) <span class="keyword">if</span> <span class="number">0</span> <span class="keyword">in</span> i <span class="keyword">else</span> i <span class="keyword">for</span> i <span class="keyword">in</span> matrix]</span><br><span class="line">        col = [[<span class="number">0</span>] * <span class="built_in">len</span>(j) <span class="keyword">if</span> <span class="number">0</span> <span class="keyword">in</span> j <span class="keyword">else</span> <span class="built_in">list</span>(j) <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">zip</span>(*matrix)]</span><br><span class="line">        col2row = <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="built_in">list</span>, <span class="built_in">zip</span>(*col)))</span><br><span class="line">        <span class="comment"># 上面一行效果等同：</span></span><br><span class="line">        <span class="comment"># col2row = [list(i) for i in zip(*col)]</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(matrix)):</span><br><span class="line">            matrix[i] = col2row[i] <span class="keyword">if</span> row[i] != [<span class="number">0</span>] * <span class="built_in">len</span>(matrix[<span class="number">0</span>]) <span class="keyword">else</span> row[i]</span><br></pre></td></tr></table></figure>
<ul>
<li>获取每一行 / 列的值，假如有0 就整行 / 整列置为0</li>
<li>重新将列排序列表转换为行排序列表，即原来的<code>matrix</code>中有0的列全为0，行不变</li>
<li><code>zip(*col)</code> 返回的是<code>zip</code>类型，需要转换成list，其中元素类型为元组</li>
<li>所以之后做了两步转换，先将zip()返回的各个元组转换为list，在将整个转换为list</li>
<li>替换matrix各行， 如果一整行为0， 则替换为0，否则为<code>col2row</code>对应的各行</li>
</ul>
<h2 id="74-搜索二维矩阵-4行"><a href="#74-搜索二维矩阵-4行" class="headerlink" title="74. 搜索二维矩阵 4行"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/search-a-2d-matrix/">74. 搜索二维矩阵 4行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">searchMatrix</span>(<span class="params">self, matrix: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]], target: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> matrix <span class="keyword">or</span> <span class="keyword">not</span> matrix[<span class="number">0</span>]:  <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">        col = <span class="built_in">list</span>(<span class="built_in">list</span>(<span class="built_in">zip</span>(*matrix))[<span class="number">0</span>])  <span class="comment"># set() -&gt; list()</span></span><br><span class="line">        index = bisect.bisect_left(col, target, <span class="number">0</span>, <span class="built_in">len</span>(matrix)-<span class="number">1</span>)  <span class="comment"># 二分查找</span></span><br><span class="line">        <span class="keyword">return</span> target <span class="keyword">in</span> (matrix[index] + matrix[index-<span class="number">1</span>])</span><br></pre></td></tr></table></figure>
<ul>
<li>先获取首列，然后二分类找到这个数所在的行，然后进行判断</li>
</ul>
<h2 id="78-Subsets-2行"><a href="#78-Subsets-2行" class="headerlink" title="78. Subsets 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/subsets/">78. Subsets 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">subsets</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        <span class="keyword">from</span> itertools <span class="keyword">import</span> combinations</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sum</span>([<span class="built_in">list</span>(combinations(nums, i)) <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(nums) + <span class="number">1</span>)], [])</span><br></pre></td></tr></table></figure>
<h2 id="80-删除排序数组中的重复项-II-4行"><a href="#80-删除排序数组中的重复项-II-4行" class="headerlink" title="80. 删除排序数组中的重复项 II 4行"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/">80. 删除排序数组中的重复项 II 4行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">removeDuplicates</span>(<span class="params">nums: [<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(nums)-<span class="number">3</span>, -<span class="number">1</span>, -<span class="number">1</span>):</span><br><span class="line">        <span class="keyword">if</span> nums[i] == nums[i+<span class="number">1</span>] <span class="keyword">and</span> nums[i] == nums[i+<span class="number">2</span>]:</span><br><span class="line">            nums.pop(i)</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">len</span>(nums)</span><br></pre></td></tr></table></figure>
<ul>
<li>从尾部开始考虑</li>
</ul>
<h2 id="81-搜索旋转排序数组-II-1行"><a href="#81-搜索旋转排序数组-II-1行" class="headerlink" title="81. 搜索旋转排序数组 II 1行"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/">81. 搜索旋转排序数组 II 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">search</span>(<span class="params">nums: [<span class="built_in">int</span>], target: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">    <span class="keyword">return</span> target <span class="keyword">in</span> nums</span><br></pre></td></tr></table></figure>
<h2 id="83-Remove-Duplicates-from-Sorted-List-3行"><a href="#83-Remove-Duplicates-from-Sorted-List-3行" class="headerlink" title="83. Remove Duplicates from Sorted List 3行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/remove-duplicates-from-sorted-list/">83. Remove Duplicates from Sorted List 3行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">deleteDuplicates</span>(<span class="params">self, head: ListNode</span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">if</span> head:</span><br><span class="line">            head.<span class="built_in">next</span> = self.deleteDuplicates(head.<span class="built_in">next</span>)</span><br><span class="line">            <span class="keyword">return</span> head.<span class="built_in">next</span> <span class="keyword">if</span> head.<span class="built_in">next</span> <span class="keyword">and</span> head.val == head.<span class="built_in">next</span>.val <span class="keyword">else</span> head</span><br></pre></td></tr></table></figure>
<ul>
<li>如果当前节点和下一个节点的值相同，则返回第二个节点</li>
<li>在每个递归中将下一个递归结果连接到当前节点</li>
</ul>
<h2 id="88-Merge-Sorted-Array-1行"><a href="#88-Merge-Sorted-Array-1行" class="headerlink" title="88. Merge Sorted Array 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/merge-sorted-array/">88. Merge Sorted Array 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">merge</span>(<span class="params">self, nums1: <span class="type">List</span>[<span class="built_in">int</span>], m: <span class="built_in">int</span>, nums2: <span class="type">List</span>[<span class="built_in">int</span>], n: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Do not return anything, modify nums1 in-place instead.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">while</span> n &gt; <span class="number">0</span>: nums1[m+n-<span class="number">1</span>], m, n = (nums1[m-<span class="number">1</span>], m-<span class="number">1</span>, n) <span class="keyword">if</span> m <span class="keyword">and</span> nums1[m-<span class="number">1</span>] &gt; nums2[n-<span class="number">1</span>] <span class="keyword">else</span> (nums2[n-<span class="number">1</span>], m, n-<span class="number">1</span>)</span><br></pre></td></tr></table></figure>
<ul>
<li>这种题倒着算更容易</li>
<li><p>上面那行代码其实就相当于：</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">merge</span>(<span class="params">self, nums1: <span class="type">List</span>[<span class="built_in">int</span>], m: <span class="built_in">int</span>, nums2: <span class="type">List</span>[<span class="built_in">int</span>], n: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Do not return anything, modify nums1 in-place instead.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">while</span> n &gt; <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">if</span> m <span class="keyword">and</span> nums1[m-<span class="number">1</span>] &gt; nums2[n-<span class="number">1</span>]:</span><br><span class="line">                nums1[m+n-<span class="number">1</span>], m, n = nums1[m-<span class="number">1</span>], m-<span class="number">1</span>, n</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                nums1[m+n-<span class="number">1</span>], m, n = nums2[n - <span class="number">1</span>], m, n-<span class="number">1</span></span><br></pre></td></tr></table></figure>
<h2 id="89-Gray-Code-1行"><a href="#89-Gray-Code-1行" class="headerlink" title="89. Gray Code 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/gray-code/">89. Gray Code 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">grayCode</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> (<span class="keyword">lambda</span> r: r + [x | <span class="number">1</span>&lt;&lt;n-<span class="number">1</span> <span class="keyword">for</span> x <span class="keyword">in</span> r[::-<span class="number">1</span>]])(self.grayCode(n-<span class="number">1</span>)) <span class="keyword">if</span> n <span class="keyword">else</span> [<span class="number">0</span>]</span><br></pre></td></tr></table></figure></li>
<li>前4个结果：  <figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">[0]</span></span><br><span class="line"><span class="string">[0 1]</span></span><br><span class="line"><span class="string">[00 01 11 10]</span></span><br><span class="line"><span class="string">[000 001 011 010 110 111 101 100]</span></span><br></pre></td></tr></table></figure></li>
<li>递归方程：这一步结果 = 上一步结果 + 上一步结果的镜像并在每个二进制数字前面加一位1</li>
<li>&lt;&lt; 左移符号，即在二进制表示后加一位 0 ，例子：3&lt;&lt;1 等于 6<code>（011 → 110）</code>，相当于 3 * 2的1次方</li>
<li>x | 1&lt;&lt;n-1 就是在十进制数字 x 的二进制前面加一位1之后的十进制结果，比如 x = 1，有 1 | 10 等于 110</li>
<li>循环可以避免一些不必要的操作，会比递归快一些：  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">grayCode</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">	r = [<span class="number">0</span>]</span><br><span class="line">	<span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(n):</span><br><span class="line">	    r.extend([x | <span class="number">1</span>&lt;&lt;i <span class="keyword">for</span> x <span class="keyword">in</span> r[::-<span class="number">1</span>]])</span><br><span class="line">	<span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>或者直接背格雷码的公式🥶吧：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">grayCode</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> [i ^ i &gt;&gt; <span class="number">1</span>  <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span> &lt;&lt; n)]</span><br></pre></td></tr></table></figure>
<h2 id="91-Decode-Ways-4行"><a href="#91-Decode-Ways-4行" class="headerlink" title="91. Decode Ways 4行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/decode-ways/">91. Decode Ways 4行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">numDecodings</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        pp, p = <span class="number">1</span>, <span class="built_in">int</span>(s[<span class="number">0</span>] != <span class="string">&#x27;0&#x27;</span>)</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, <span class="built_in">len</span>(s)):</span><br><span class="line">            pp, p = p, pp * (<span class="number">9</span> &lt; <span class="built_in">int</span>(s[i-<span class="number">1</span>:i+<span class="number">1</span>]) &lt;= <span class="number">26</span>) + p * (<span class="built_in">int</span>(s[i]) &gt; <span class="number">0</span>)</span><br><span class="line">        <span class="keyword">return</span> p</span><br></pre></td></tr></table></figure></li>
<li>输入 ‘12’ 的结果为 2，如果我们在 ‘12’ 后面增加一个数字 3，输入变成 ‘123’，结果是 ‘12’的结果 + ‘1’的结果 = 3</li>
<li>i 从索引 1 开始逐渐遍历 s，当前位置对应结果 = 上上次结果(如果 i 位置字符和 i-1 位置字符的组合满足条件) + 上次结果(如果 s[i] 不为 0)<h2 id="94-Binary-Tree-Inorder-Traversal-2行"><a href="#94-Binary-Tree-Inorder-Traversal-2行" class="headerlink" title="94. Binary Tree Inorder Traversal 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/binary-tree-inorder-traversal/">94. Binary Tree Inorder Traversal 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">inorderTraversal</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        f = self.inorderTraversal</span><br><span class="line">        <span class="keyword">return</span> f(root.left) + [root.val] + f(root.right) <span class="keyword">if</span> root <span class="keyword">else</span> []</span><br></pre></td></tr></table></figure></li>
<li>递归<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">inorderTraversal</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        r, stack = [], []</span><br><span class="line">        <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">            <span class="keyword">while</span> root:</span><br><span class="line">                stack.append(root)</span><br><span class="line">                root = root.left</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> stack:</span><br><span class="line">                <span class="keyword">return</span> r</span><br><span class="line">            node = stack.pop()</span><br><span class="line">            r.append(node.val)</span><br><span class="line">            root = node.right</span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>迭代<h2 id="98-Validate-Binary-Search-Tree-3行"><a href="#98-Validate-Binary-Search-Tree-3行" class="headerlink" title="98. Validate Binary Search Tree 3行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/validate-binary-search-tree/">98. Validate Binary Search Tree 3行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isValidBST</span>(<span class="params">self, root: TreeNode, first=<span class="literal">True</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root: <span class="keyword">return</span> first <span class="keyword">or</span> []</span><br><span class="line">        l = self.isValidBST(root.left, <span class="number">0</span>) + [root.val] + self.isValidBST(root.right, <span class="number">0</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">all</span>([a &gt; b <span class="keyword">for</span> a, b <span class="keyword">in</span> <span class="built_in">zip</span>(l[<span class="number">1</span>:], l)]) <span class="keyword">if</span> first <span class="keyword">else</span> l</span><br></pre></td></tr></table></figure></li>
<li>搜索二叉树的中序遍历结果呈升序<h2 id="101-Symmetric-Tree-5行"><a href="#101-Symmetric-Tree-5行" class="headerlink" title="101. Symmetric Tree 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/symmetric-tree/">101. Symmetric Tree 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isSymmetric</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root <span class="keyword">or</span> root.left <span class="keyword">is</span> root.right: <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">        l, r, i, o = root.left, root.right, TreeNode(<span class="number">0</span>), TreeNode(<span class="number">0</span>)</span><br><span class="line">        <span class="keyword">if</span> (l <span class="keyword">and</span> l.val) != (r <span class="keyword">and</span> r.val): <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">        i.left, i.right, o.left, o.right = l.left, r.right, l.right, r.left</span><br><span class="line">        <span class="keyword">return</span> self.isSymmetric(i) <span class="keyword">and</span> self.isSymmetric(o)</span><br></pre></td></tr></table></figure></li>
<li>一棵树对称意味着：<ul>
<li>左节点 == 右节点</li>
<li>左节点的左子树与右节点右子树对称</li>
<li>左节点的右子树与右节点左子树对称</li>
</ul>
</li>
<li>前三行处理特殊情况：root为None或root无子节点直接返回True，root只有一个子节点或root两个子节点不相等直接返回False</li>
<li>第一个条件在前三行处理过了，对于第二和第三个条件，我们分别构造两个假树i(inner)和o(outer)，i代表内假树，对应条件二，o代表外假树，对应条件三。递归内外假树即可<h2 id="104-Maximum-Depth-of-Binary-Tree-1行"><a href="#104-Maximum-Depth-of-Binary-Tree-1行" class="headerlink" title="104. Maximum Depth of Binary Tree 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/maximum-depth-of-binary-tree/">104. Maximum Depth of Binary Tree 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">maxDepth</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">max</span>(<span class="built_in">map</span>(self.maxDepth,(root.left, root.right))) + <span class="number">1</span> <span class="keyword">if</span> root <span class="keyword">else</span> <span class="number">0</span></span><br></pre></td></tr></table></figure></li>
<li>利用map函数递归左右节点获取最大值，map函数会将参数一所指向的函数应用于参数二里的所有对象并返回所有结果构成的迭代器<h2 id="110-平衡二叉树-3行"><a href="#110-平衡二叉树-3行" class="headerlink" title="110. 平衡二叉树 3行"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/balanced-binary-tree/">110. 平衡二叉树 3行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isBalanced</span>(<span class="params">self, root: TreeNode, first=<span class="literal">True</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root: <span class="keyword">return</span> first <span class="keyword">or</span> <span class="number">0</span></span><br><span class="line">        l, r = <span class="built_in">map</span>(<span class="keyword">lambda</span> x: self.isBalanced(x, <span class="literal">False</span>), [root.left, root.right])</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">max</span>(l,r)+<span class="number">1</span> <span class="keyword">if</span> <span class="built_in">min</span>(l,r)&gt;-<span class="number">1</span> <span class="keyword">and</span> <span class="built_in">abs</span>(l-r)&lt;=<span class="number">1</span> <span class="keyword">else</span> (-<span class="number">1</span>, <span class="literal">False</span>)[first]</span><br></pre></td></tr></table></figure></li>
<li>DFS递归每个节点</li>
<li>如果这个节点不平衡，那么这棵树肯定不平衡，它和它的所有父节点都返回 -1（根节点返回False）</li>
<li>如果节点平衡，则返回当前树的高度 + 1（根节点返回True）<h2 id="112-Path-Sum-3行"><a href="#112-Path-Sum-3行" class="headerlink" title="112. Path Sum 3行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/path-sum/">112. Path Sum 3行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">hasPathSum</span>(<span class="params">self, root: TreeNode, <span class="built_in">sum</span>: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root: <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">        l, r, f = root.left, root.right, <span class="keyword">lambda</span> x: self.hasPathSum(x, <span class="built_in">sum</span> - root.val)</span><br><span class="line">        <span class="keyword">return</span> l <span class="keyword">is</span> r <span class="keyword">and</span> <span class="built_in">sum</span> == root.val <span class="keyword">or</span> f(l) <span class="keyword">or</span> f(r)</span><br></pre></td></tr></table></figure></li>
<li>考虑初始状态：当树不存在时直接返回 False</li>
<li>考虑支路1：当前节点为叶节点时直接判断总和是否达到要求</li>
<li>考虑支路2：当前节点为非叶节点时将总和缩小并继续递归，判断左右节点是否存在满足条件的</li>
<li>当递归函数到达叶节点时，sum 已经被削减了多次，此时 <code>sum - node.val</code> 即为 <code>原始的sum - 整条路径的总和</code><h2 id="118-Pascal’s-Triangle-1行"><a href="#118-Pascal’s-Triangle-1行" class="headerlink" title="118. Pascal’s Triangle 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/pascals-triangle/">118. Pascal’s Triangle 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">generate</span>(<span class="params">self, numRows: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        <span class="keyword">return</span> [[math.factorial(i)//math.factorial(i-j)//math.factorial(j) <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(i+<span class="number">1</span>)] <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(numRows)]</span><br></pre></td></tr></table></figure></li>
<li>参考了杨辉三角的数学性质，<a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Pascal%27s_triangle">维基百科</a></li>
<li>正常迭代方法：  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">generate</span>(<span class="params">self, numRows: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">	r = [[<span class="number">1</span>]]</span><br><span class="line">	<span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, numRows):</span><br><span class="line">	    r.append([<span class="number">1</span>] + [<span class="built_in">sum</span>(r[-<span class="number">1</span>][j:j+<span class="number">2</span>]) <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(i)])</span><br><span class="line">	<span class="keyword">return</span> numRows <span class="keyword">and</span> r <span class="keyword">or</span> []</span><br></pre></td></tr></table></figure>
<h2 id="121-Best-Time-to-Buy-and-Sell-Stock-2行"><a href="#121-Best-Time-to-Buy-and-Sell-Stock-2行" class="headerlink" title="121. Best Time to Buy and Sell Stock 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/">121. Best Time to Buy and Sell Stock 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">maxProfit</span>(<span class="params">self, prices: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">from</span> functools <span class="keyword">import</span> reduce</span><br><span class="line">        <span class="keyword">return</span> reduce(<span class="keyword">lambda</span> r, p: (<span class="built_in">max</span>(r[<span class="number">0</span>], p-r[<span class="number">1</span>]), <span class="built_in">min</span>(r[<span class="number">1</span>], p)), prices, (<span class="number">0</span>, <span class="built_in">float</span>(<span class="string">&#x27;inf&#x27;</span>)))[<span class="number">0</span>]</span><br></pre></td></tr></table></figure></li>
<li>r = (结果，之前遍历过的所有元素中的最小值)</li>
<li><a target="_blank" rel="noopener" href="https://www.cnblogs.com/XXCXY/p/5180245.html">reduce 函数详解</a><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">maxProfit</span>(<span class="params">self, prices: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        r, m = <span class="number">0</span>, <span class="built_in">float</span>(<span class="string">&#x27;inf&#x27;</span>)</span><br><span class="line">        <span class="keyword">for</span> p <span class="keyword">in</span> prices:</span><br><span class="line">            r, m = <span class="built_in">max</span>(r, p - m), <span class="built_in">min</span>(m, p)</span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure>
<h2 id="122-Best-Time-to-Buy-and-Sell-Stock-II-2行"><a href="#122-Best-Time-to-Buy-and-Sell-Stock-II-2行" class="headerlink" title="122. Best Time to Buy and Sell Stock II 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/">122. Best Time to Buy and Sell Stock II 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">maxProfit</span>(<span class="params">self, prices: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sum</span>(b - a <span class="keyword">for</span> a, b <span class="keyword">in</span> <span class="built_in">zip</span>(prices, prices[<span class="number">1</span>:]) <span class="keyword">if</span> b &gt; a)</span><br></pre></td></tr></table></figure></li>
<li>本题可以在同一天买入和卖出，因此只要当天票价比昨天的高就可以卖出<h2 id="124-Binary-Tree-Maximum-Path-Sum-4行"><a href="#124-Binary-Tree-Maximum-Path-Sum-4行" class="headerlink" title="124. Binary Tree Maximum Path Sum 4行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/binary-tree-maximum-path-sum/">124. Binary Tree Maximum Path Sum 4行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">maxPathSum</span>(<span class="params">self, root: TreeNode, ok=<span class="literal">True</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root: <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">        l, r = self.maxPathSum(root.left, <span class="literal">False</span>), self.maxPathSum(root.right, <span class="literal">False</span>)</span><br><span class="line">        self.<span class="built_in">max</span> = <span class="built_in">max</span>(<span class="built_in">getattr</span>(self, <span class="string">&#x27;max&#x27;</span>, <span class="built_in">float</span>(<span class="string">&#x27;-inf&#x27;</span>)), l + root.val + r)</span><br><span class="line">        <span class="keyword">return</span> self.<span class="built_in">max</span> <span class="keyword">if</span> ok <span class="keyword">else</span> <span class="built_in">max</span>(root.val + <span class="built_in">max</span>(l, r), <span class="number">0</span>)</span><br></pre></td></tr></table></figure></li>
<li>使用 <code>self.max</code> 记录全局最大值，<code>getattr</code> 返回自身 <code>max</code> 属性的值或预定义的负无穷</li>
<li>本题思路是：递归每一个节点，返回<code>max(以当前节点为结尾的最大路径和,0)</code>。并更新最大值<code>全局最大路径和=max(全局最大路径和，当前节点值+左子树返回结果+右子树返回结果)</code></li>
<li>用<code>ok</code>判断是不是第一次递归，是就返回全局最大值，否则照常<h2 id="133-Clone-Graph"><a href="#133-Clone-Graph" class="headerlink" title="133. Clone Graph"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/clone-graph/">133. Clone Graph</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string"># Definition for a Node.</span></span><br><span class="line"><span class="string">class Node:</span></span><br><span class="line"><span class="string">    def __init__(self, val, neighbors):</span></span><br><span class="line"><span class="string">        self.val = val</span></span><br><span class="line"><span class="string">        self.neighbors = neighbors</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">cloneGraph</span>(<span class="params">self, node: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="string">&#x27;Node&#x27;</span>:</span><br><span class="line">        <span class="keyword">return</span> copy.deepcopy(node)</span><br></pre></td></tr></table></figure></li>
<li>dfs解法请参考 <a href="#133-克隆图">133克隆图</a><h2 id="136-Single-Number-2行"><a href="#136-Single-Number-2行" class="headerlink" title="136. Single Number 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/single-number/">136. Single Number 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">singleNumber</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">from</span> functools <span class="keyword">import</span> reduce</span><br><span class="line">        <span class="keyword">return</span> reduce(<span class="built_in">int</span>.__xor__, nums)</span><br></pre></td></tr></table></figure></li>
<li>这里用到了异或（xor），相同的数字异或后为0，0异或任何数都等于那个数，用reduce在列表所有元素之间使用异或^，那么留下的就是那个单独的数字了<h2 id="138-Copy-List-with-Random-Pointer-1行"><a href="#138-Copy-List-with-Random-Pointer-1行" class="headerlink" title="138. Copy List with Random Pointer 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/copy-list-with-random-pointer/">138. Copy List with Random Pointer 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string"># Definition for a Node.</span></span><br><span class="line"><span class="string">class Node:</span></span><br><span class="line"><span class="string">    def __init__(self, val, next, random):</span></span><br><span class="line"><span class="string">        self.val = val</span></span><br><span class="line"><span class="string">        self.next = next</span></span><br><span class="line"><span class="string">        self.random = random</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">copyRandomList</span>(<span class="params">self, head: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="string">&#x27;Node&#x27;</span>:</span><br><span class="line">        <span class="keyword">return</span> copy.deepcopy(head)</span><br></pre></td></tr></table></figure></li>
<li>内置函数<h2 id="139-Word-Break-8行"><a href="#139-Word-Break-8行" class="headerlink" title="139. Word Break 8行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/word-break/">139. Word Break 8行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">wordBreak</span>(<span class="params">self, s, wordDict</span>):</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">f</span>(<span class="params">s, d=&#123;&#125;</span>):</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> s <span class="keyword">in</span> d:</span><br><span class="line">                <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, <span class="number">1</span> + <span class="built_in">len</span>(s)):</span><br><span class="line">                    d[s[:i]] = s[:i] <span class="keyword">in</span> wordDict <span class="keyword">and</span> (i == <span class="built_in">len</span>(s) <span class="keyword">or</span> f(s[i:]))</span><br><span class="line">                    <span class="keyword">if</span> d[s[:i]]: <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">                <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">            <span class="keyword">return</span> d[s]</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> f(s)</span><br></pre></td></tr></table></figure></li>
<li>brute force + memory<h2 id="141-Linked-List-Cycle-2行"><a href="#141-Linked-List-Cycle-2行" class="headerlink" title="141. Linked List Cycle 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/linked-list-cycle/">141. Linked List Cycle 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode(object):</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">hasCycle</span>(<span class="params">self, head</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        :type head: ListNode</span></span><br><span class="line"><span class="string">        :rtype: bool</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">while</span> head <span class="keyword">and</span> head.val != <span class="literal">None</span>: head.val, head = <span class="literal">None</span>, head.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">return</span> head != <span class="literal">None</span></span><br></pre></td></tr></table></figure></li>
<li>这题不支持python3，所以用pyhton2解法代替，下题记得调回来</li>
<li>破坏走过的所有节点，下次再遇到就知道了</li>
<li>不过以上方法会丢失原有信息，一般解法为快慢指针<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode(object):</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">hasCycle</span>(<span class="params">self, head</span>):</span><br><span class="line">        slow = fast = head</span><br><span class="line">        <span class="keyword">while</span> fast <span class="keyword">and</span> fast.<span class="built_in">next</span>:</span><br><span class="line">            fast = fast.<span class="built_in">next</span>.<span class="built_in">next</span></span><br><span class="line">            slow = slow.<span class="built_in">next</span></span><br><span class="line">            <span class="keyword">if</span> slow == fast:</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">        <span class="keyword">return</span> <span class="literal">False</span></span><br></pre></td></tr></table></figure>
<h2 id="142-Linked-List-Cycle-II-5行"><a href="#142-Linked-List-Cycle-II-5行" class="headerlink" title="142. Linked List Cycle II 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/linked-list-cycle-ii/">142. Linked List Cycle II 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode(object):</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">detectCycle</span>(<span class="params">self, head</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        :type head: ListNode</span></span><br><span class="line"><span class="string">        :rtype: ListNode</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        s = &#123;<span class="literal">None</span>&#125;</span><br><span class="line">        <span class="keyword">while</span> head <span class="keyword">not</span> <span class="keyword">in</span> s:</span><br><span class="line">            s.add(head)</span><br><span class="line">            head = head.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">return</span> head</span><br></pre></td></tr></table></figure></li>
<li>把见过的节点丢集合里，下次再遇见就是环的开始</li>
<li>还有一个纯数学的快慢指针解法，设环的起始节点为 E，快慢指针从 head 出发，快指针速度为 2，设相交节点为 X，head 到 E 的距离为 H，E 到 X 的距离为 D，环的长度为 L，那么有：快指针走过的距离等于慢指针走过的距离加快指针多走的距离（多走了 n 圈的 L） <code>2(H + D) = H + D + nL</code>，因此可以推出 <code>H = nL - D</code>，这意味着如果我们让俩个慢指针一个从 head 出发，一个从 X 出发的话，他们一定会在节点 E 相遇  <figure class="highlight asciidoc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="code">	  _____</span></span><br><span class="line"><span class="code">	 /     \</span></span><br><span class="line">head<span class="emphasis">_____</span><span class="emphasis">_____</span><span class="emphasis">_E       \</span></span><br><span class="line"><span class="emphasis">	\       /</span></span><br><span class="line"><span class="emphasis">	 X_____</span>/ </span><br></pre></td></tr></table></figure>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">detectCycle</span>(<span class="params">self, head</span>):</span><br><span class="line">	slow = fast = head</span><br><span class="line">	<span class="keyword">while</span> fast <span class="keyword">and</span> fast.<span class="built_in">next</span>:</span><br><span class="line">	    fast = fast.<span class="built_in">next</span>.<span class="built_in">next</span></span><br><span class="line">	    slow = slow.<span class="built_in">next</span></span><br><span class="line">	    <span class="keyword">if</span> slow == fast:</span><br><span class="line">		<span class="keyword">break</span></span><br><span class="line">	<span class="keyword">else</span>:</span><br><span class="line">	    <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line">	<span class="keyword">while</span> head <span class="keyword">is</span> <span class="keyword">not</span> slow:</span><br><span class="line">	    head = head.<span class="built_in">next</span></span><br><span class="line">	    slow = slow.<span class="built_in">next</span></span><br><span class="line">	<span class="keyword">return</span> head</span><br></pre></td></tr></table></figure>
<h2 id="146-LRU-Cache-7行"><a href="#146-LRU-Cache-7行" class="headerlink" title="146. LRU Cache 7行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/lru-cache/">146. LRU Cache 7行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">LRUCache</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, capacity</span>):</span><br><span class="line">        self.od, self.cap = collections.OrderedDict(), capacity</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">get</span>(<span class="params">self, key</span>):</span><br><span class="line">        <span class="keyword">if</span> key <span class="keyword">not</span> <span class="keyword">in</span> self.od: <span class="keyword">return</span> -<span class="number">1</span></span><br><span class="line">        self.od.move_to_end(key)</span><br><span class="line">        <span class="keyword">return</span> self.od[key]</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">put</span>(<span class="params">self, key, value</span>):</span><br><span class="line">        <span class="keyword">if</span> key <span class="keyword">in</span> self.od: <span class="keyword">del</span> self.od[key]</span><br><span class="line">        <span class="keyword">elif</span> <span class="built_in">len</span>(self.od) == self.cap: self.od.popitem(<span class="literal">False</span>)</span><br><span class="line">        self.od[key] = value</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your LRUCache object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = LRUCache(capacity)</span></span><br><span class="line"><span class="comment"># param_1 = obj.get(key)</span></span><br><span class="line"><span class="comment"># obj.put(key,value)</span></span><br></pre></td></tr></table></figure>
<h2 id="148-Sort-List-10行"><a href="#148-Sort-List-10行" class="headerlink" title="148. Sort List 10行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/sort-list/">148. Sort List 10行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">sortList</span>(<span class="params">self, head: ListNode</span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> (head <span class="keyword">and</span> head.<span class="built_in">next</span>): <span class="keyword">return</span> head</span><br><span class="line">        pre, slow, fast = <span class="literal">None</span>, head, head</span><br><span class="line">        <span class="keyword">while</span> fast <span class="keyword">and</span> fast.<span class="built_in">next</span>: pre, slow, fast = slow, slow.<span class="built_in">next</span>, fast.<span class="built_in">next</span>.<span class="built_in">next</span></span><br><span class="line">        pre.<span class="built_in">next</span> = <span class="literal">None</span></span><br><span class="line">        <span class="keyword">return</span> self.mergeTwoLists(*<span class="built_in">map</span>(self.sortList, (head, slow)))</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">mergeTwoLists</span>(<span class="params">self, l1: ListNode, l2: ListNode</span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">if</span> l1 <span class="keyword">and</span> l2:</span><br><span class="line">            <span class="keyword">if</span> l1.val &gt; l2.val: l1, l2 = l2, l1</span><br><span class="line">            l1.<span class="built_in">next</span> = self.mergeTwoLists(l1.<span class="built_in">next</span>, l2)</span><br><span class="line">        <span class="keyword">return</span> l1 <span class="keyword">or</span> l2</span><br></pre></td></tr></table></figure></li>
<li>使用快慢指针寻找链表中点，并分解链表</li>
<li>递归融合俩个有序链表，详解见 21 题</li>
<li>此处忽略了递归开栈导致的非 常数级空间复杂度（想太多了吧），如果一定要抬杠，推荐使用<code>quicksort</code>  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">sortList</span>(<span class="params">self, head</span>):</span><br><span class="line">	<span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">	:type head: ListNode</span></span><br><span class="line"><span class="string">	:rtype: ListNode</span></span><br><span class="line"><span class="string">	&quot;&quot;&quot;</span></span><br><span class="line">	<span class="keyword">def</span> <span class="title function_">partition</span>(<span class="params">start, end</span>):</span><br><span class="line">	    node = start.<span class="built_in">next</span>.<span class="built_in">next</span></span><br><span class="line">	    pivotPrev = start.<span class="built_in">next</span></span><br><span class="line">	    pivotPrev.<span class="built_in">next</span> = end</span><br><span class="line">	    pivotPost = pivotPrev</span><br><span class="line">	    <span class="keyword">while</span> node != end:</span><br><span class="line">		temp = node.<span class="built_in">next</span></span><br><span class="line">		<span class="keyword">if</span> node.val &gt; pivotPrev.val:</span><br><span class="line">		    node.<span class="built_in">next</span> = pivotPost.<span class="built_in">next</span></span><br><span class="line">		    pivotPost.<span class="built_in">next</span> = node</span><br><span class="line">		<span class="keyword">elif</span> node.val &lt; pivotPrev.val:</span><br><span class="line">		    node.<span class="built_in">next</span> = start.<span class="built_in">next</span></span><br><span class="line">		    start.<span class="built_in">next</span> = node</span><br><span class="line">		<span class="keyword">else</span>:</span><br><span class="line">		    node.<span class="built_in">next</span> = pivotPost.<span class="built_in">next</span></span><br><span class="line">		    pivotPost.<span class="built_in">next</span> = node</span><br><span class="line">		    pivotPost = pivotPost.<span class="built_in">next</span></span><br><span class="line">		node = temp</span><br><span class="line">	    <span class="keyword">return</span> [pivotPrev, pivotPost]</span><br><span class="line"></span><br><span class="line">	<span class="keyword">def</span> <span class="title function_">quicksort</span>(<span class="params">start, end</span>):</span><br><span class="line">	    <span class="keyword">if</span> start.<span class="built_in">next</span> != end:</span><br><span class="line">		prev, post = partition(start, end)</span><br><span class="line">		quicksort(start, prev)</span><br><span class="line">		quicksort(post, end)</span><br><span class="line"></span><br><span class="line">	newHead = ListNode(<span class="number">0</span>)</span><br><span class="line">	newHead.<span class="built_in">next</span> = head</span><br><span class="line">	quicksort(newHead, <span class="literal">None</span>)</span><br><span class="line">	<span class="keyword">return</span> newHead.<span class="built_in">next</span></span><br></pre></td></tr></table></figure>
<h2 id="150-Evaluate-Reverse-Polish-Notation-5行"><a href="#150-Evaluate-Reverse-Polish-Notation-5行" class="headerlink" title="150. Evaluate Reverse Polish Notation 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/evaluate-reverse-polish-notation/">150. Evaluate Reverse Polish Notation 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">evalRPN</span>(<span class="params">self, tokens: <span class="type">List</span>[<span class="built_in">str</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        t, f = tokens.pop(), self.evalRPN</span><br><span class="line">        <span class="keyword">if</span> t <span class="keyword">in</span> <span class="string">&#x27;+-*/&#x27;</span>:</span><br><span class="line">            b, a = f(tokens), f(tokens)</span><br><span class="line">            t = <span class="built_in">eval</span>(<span class="string">&#x27;a&#x27;</span> + t + <span class="string">&#x27;b&#x27;</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">int</span>(t)</span><br></pre></td></tr></table></figure></li>
<li>递归地返回左右表达式操作后结果</li>
<li><code>eval</code> 函数将字符串看作代码得到输出值<h2 id="155-Min-Stack-每个1行"><a href="#155-Min-Stack-每个1行" class="headerlink" title="155. Min Stack 每个1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/min-stack/">155. Min Stack 每个1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">MinStack</span>:</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        self.data = [(<span class="literal">None</span>, <span class="built_in">float</span>(<span class="string">&#x27;inf&#x27;</span>))]</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">push</span>(<span class="params">self, x: <span class="string">&#x27;int&#x27;</span></span>) -&gt; <span class="string">&#x27;None&#x27;</span>:</span><br><span class="line">        self.data.append((x, <span class="built_in">min</span>(x, self.data[-<span class="number">1</span>][<span class="number">1</span>])))</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pop</span>(<span class="params">self</span>) -&gt; <span class="string">&#x27;None&#x27;</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">len</span>(self.data) &gt; <span class="number">1</span>: self.data.pop()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">top</span>(<span class="params">self</span>) -&gt; <span class="string">&#x27;int&#x27;</span>:</span><br><span class="line">        <span class="keyword">return</span> self.data[-<span class="number">1</span>][<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">getMin</span>(<span class="params">self</span>) -&gt; <span class="string">&#x27;int&#x27;</span>:</span><br><span class="line">        <span class="keyword">return</span> self.data[-<span class="number">1</span>][<span class="number">1</span>]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your MinStack object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = MinStack()</span></span><br><span class="line"><span class="comment"># obj.push(x)</span></span><br><span class="line"><span class="comment"># obj.pop()</span></span><br><span class="line"><span class="comment"># param_3 = obj.top()</span></span><br><span class="line"><span class="comment"># param_4 = obj.getMin()</span></span><br></pre></td></tr></table></figure>
<h2 id="160-Intersection-of-Two-Linked-Lists-3行"><a href="#160-Intersection-of-Two-Linked-Lists-3行" class="headerlink" title="160. Intersection of Two Linked Lists 3行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/intersection-of-two-linked-lists/">160. Intersection of Two Linked Lists 3行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode(object):</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">getIntersectionNode</span>(<span class="params">self, headA, headB</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        :type head1, head1: ListNode</span></span><br><span class="line"><span class="string">        :rtype: ListNode</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        a, b = (headA, headB) <span class="keyword">if</span> headA <span class="keyword">and</span> headB <span class="keyword">else</span> (<span class="literal">None</span>, <span class="literal">None</span>)</span><br><span class="line">        <span class="keyword">while</span> a != b: a, b = <span class="keyword">not</span> a <span class="keyword">and</span> headB <span class="keyword">or</span> a.<span class="built_in">next</span>, <span class="keyword">not</span> b <span class="keyword">and</span> headA <span class="keyword">or</span> b.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">return</span> a</span><br></pre></td></tr></table></figure></li>
<li>这题不支持 Python3 所以只能用 Python2 做了</li>
<li>把第一条链表的尾部接到第二条链表的开头，第二条接到第一条的开头，就能消除俩条链表的长度差，并在某一时刻在第一个交叉点相遇，或在走完俩条链表长度的时候同时为 <code>None</code>  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 假设有两条链表1→2→3→4和①→②→③，模拟一下算法流程 ↓</span></span><br><span class="line"></span><br><span class="line"><span class="number">1</span> → <span class="number">2</span> ↘  ↗ → <span class="number">4</span>                               <span class="number">1</span> → <span class="number">2</span> ↘  ↗ → <span class="number">4</span> → ① → → → <span class="number">3</span>(②) ❤ 相遇了</span><br><span class="line">① → → → <span class="number">3</span>(②) → ③   把<span class="number">4</span>接到①前面，把③接到<span class="number">1</span>前面   ① → → → <span class="number">3</span>(②) → ③ → <span class="number">1</span> → <span class="number">2</span> ↗     若非相交链表则同时走到<span class="literal">None</span></span><br></pre></td></tr></table></figure>
<h2 id="162-Find-Peak-Element-2行"><a href="#162-Find-Peak-Element-2行" class="headerlink" title="162. Find Peak Element 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/find-peak-element/">162. Find Peak Element 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findPeakElement</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        self.__class__.__getitem__ = <span class="keyword">lambda</span> self, i: i <span class="keyword">and</span> nums[i - <span class="number">1</span>] &gt; nums[i]</span><br><span class="line">        <span class="keyword">return</span> bisect.bisect_left(self, <span class="literal">True</span>, <span class="number">0</span>, <span class="built_in">len</span>(nums)) - <span class="number">1</span></span><br></pre></td></tr></table></figure></li>
<li><a href="#-%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE">二分查找套路</a></li>
<li>如果当前位置的左边是更大的数字，则当前位置置为True，继续向左搜索，最后应该插入的位置 = 我们寻找的位置 + 1，因此最后 - 1<h2 id="165-Compare-Version-Numbers-4行"><a href="#165-Compare-Version-Numbers-4行" class="headerlink" title="165. Compare Version Numbers 4行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/compare-version-numbers/">165. Compare Version Numbers 4行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">compareVersion</span>(<span class="params">self, version1: <span class="built_in">str</span>, version2: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        v1, v2 = [*<span class="built_in">map</span>(<span class="built_in">int</span>, version1.split(<span class="string">&#x27;.&#x27;</span>))], [*<span class="built_in">map</span>(<span class="built_in">int</span>, version2.split(<span class="string">&#x27;.&#x27;</span>))]</span><br><span class="line">        d = <span class="built_in">len</span>(v2) - <span class="built_in">len</span>(v1)</span><br><span class="line">        v1, v2 = v1 + [<span class="number">0</span>] * d, v2 + [<span class="number">0</span>] * -d</span><br><span class="line">        <span class="keyword">return</span> (v1 &gt; v2) - (v1 &lt; v2)</span><br></pre></td></tr></table></figure></li>
<li>利用 python 序列比较的性质<h2 id="169-Majority-Element-1行"><a href="#169-Majority-Element-1行" class="headerlink" title="169. Majority Element 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/majority-element/">169. Majority Element 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">majorityElement</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sorted</span>(nums)[<span class="built_in">len</span>(nums) // <span class="number">2</span>]</span><br></pre></td></tr></table></figure>
<h2 id="171-Excel-Sheet-Column-Number-1行"><a href="#171-Excel-Sheet-Column-Number-1行" class="headerlink" title="171. Excel Sheet Column Number 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/excel-sheet-column-number/">171. Excel Sheet Column Number 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">titleToNumber</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sum</span>((<span class="built_in">ord</span>(c) - <span class="number">64</span>) * <span class="number">26</span>**i <span class="keyword">for</span> i, c <span class="keyword">in</span> <span class="built_in">enumerate</span>(s[::-<span class="number">1</span>]))</span><br></pre></td></tr></table></figure>
<h2 id="173-Binary-Search-Tree-Iterator-6行"><a href="#173-Binary-Search-Tree-Iterator-6行" class="headerlink" title="173. Binary Search Tree Iterator 6行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/binary-search-tree-iterator/">173. Binary Search Tree Iterator 6行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">BSTIterator</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, root: TreeNode</span>):</span><br><span class="line">        self.s = []</span><br><span class="line">        <span class="keyword">while</span> root: self.s[<span class="built_in">len</span>(self.s):], root = [root], root.left</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">next</span>(<span class="params">self</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        @return the next smallest number</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        r, root = self.s[-<span class="number">1</span>], self.s.pop().right</span><br><span class="line">        <span class="keyword">while</span> root: self.s[<span class="built_in">len</span>(self.s):], root = [root], root.left</span><br><span class="line">        <span class="keyword">return</span> r.val</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">hasNext</span>(<span class="params">self</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        @return whether we have a next smallest number</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">bool</span>(self.s)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your BSTIterator object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = BSTIterator(root)</span></span><br><span class="line"><span class="comment"># param_1 = obj.next()</span></span><br><span class="line"><span class="comment"># param_2 = obj.hasNext()</span></span><br></pre></td></tr></table></figure></li>
<li>模拟中序遍历的迭代过程，使用堆栈 <code>self.s</code> 进行深度优先搜索</li>
<li>空间复杂度为 O(树的高度)</li>
<li>$平均时间复杂度 = \frac {循环总次数（N）}{迭代器长度（N）} = O(1)$</li>
<li>迭代器解法：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> itertools <span class="keyword">import</span> chain</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">BSTIterator</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, root: TreeNode</span>):</span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">gen</span>(<span class="params">root</span>): <span class="keyword">yield</span> <span class="keyword">from</span> chain(gen(root.left), [root.val], gen(root.right)) <span class="keyword">if</span> root <span class="keyword">else</span> ()</span><br><span class="line">        self.<span class="built_in">iter</span>, self.<span class="built_in">len</span> = gen(root), <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> _ <span class="keyword">in</span> gen(root): self.<span class="built_in">len</span> += <span class="number">1</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">next</span>(<span class="params">self</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        @return the next smallest number</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.<span class="built_in">len</span> -= <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">next</span>(self.<span class="built_in">iter</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">hasNext</span>(<span class="params">self</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        @return whether we have a next smallest number</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">bool</span>(self.<span class="built_in">len</span>)</span><br></pre></td></tr></table></figure></li>
<li>平均时空复杂度： $O(1)$，$O(1)$<h2 id="189-Rotate-Array-1行"><a href="#189-Rotate-Array-1行" class="headerlink" title="189. Rotate Array 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/rotate-array/">189. Rotate Array 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">rotate</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], k: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Do not return anything, modify nums in-place instead.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        nums[:] = nums[<span class="built_in">len</span>(nums) - k:] + nums[:<span class="built_in">len</span>(nums) - k]</span><br></pre></td></tr></table></figure></li>
<li>空间复杂度 = $O(N)$</li>
<li>进阶：  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">rotate</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], k: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">	<span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">	Do not return anything, modify nums in-place instead.</span></span><br><span class="line"><span class="string">	&quot;&quot;&quot;</span></span><br><span class="line">	<span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(k % <span class="built_in">len</span>(nums)): nums[-<span class="number">1</span>:], nums[:<span class="number">0</span>] = [], nums[-<span class="number">1</span>:]</span><br></pre></td></tr></table></figure>
<ul>
<li>时间复杂度 = $O(k \;\%\; len(nums))$，空间复杂度 = $O(1)$<h2 id="190-Reverse-Bits-1行"><a href="#190-Reverse-Bits-1行" class="headerlink" title="190. Reverse Bits 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/reverse-bits/">190. Reverse Bits 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="comment"># @param n, an integer</span></span><br><span class="line">    <span class="comment"># @return an integer</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">reverseBits</span>(<span class="params">self, n</span>):</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">int</span>(<span class="built_in">bin</span>(n)[<span class="number">2</span>:].zfill(<span class="number">32</span>)[::-<span class="number">1</span>], <span class="number">2</span>)</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li>字符串操作</li>
<li><a target="_blank" rel="noopener" href="https://www.runoob.com/python/att-string-zfill.html">ziff用法</a><h2 id="191-Number-of-1-Bits-1行"><a href="#191-Number-of-1-Bits-1行" class="headerlink" title="191. Number of 1 Bits 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/number-of-1-bits/">191. Number of 1 Bits 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">hammingWeight</span>(<span class="params">self, n</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        :type n: int</span></span><br><span class="line"><span class="string">        :rtype: int</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">bin</span>(n).count(<span class="string">&#x27;1&#x27;</span>)</span><br></pre></td></tr></table></figure>
<h2 id="198-House-Robber-2行"><a href="#198-House-Robber-2行" class="headerlink" title="198. House Robber 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/house-robber/">198. House Robber 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">rob</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">from</span> functools <span class="keyword">import</span> reduce</span><br><span class="line">        <span class="keyword">return</span> reduce(<span class="keyword">lambda</span> r, n: (<span class="built_in">max</span>(r[<span class="number">0</span>], n + r[<span class="number">1</span>]), r[<span class="number">0</span>]), nums, (<span class="number">0</span>, <span class="number">0</span>))[<span class="number">0</span>]</span><br></pre></td></tr></table></figure></li>
<li>DP递归方程：一直偷到这家的钱 = max（一直偷到上一家的钱，一直偷到上上家的钱 + 这家的钱）😃有点小绕</li>
<li>以上为下面代码的化简版，<a target="_blank" rel="noopener" href="https://www.cnblogs.com/XXCXY/p/5180245.html">reduce 函数详解</a><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">rob</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        last, now = <span class="number">0</span>, <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> nums:</span><br><span class="line">            last, now = now, <span class="built_in">max</span>(last + i, now)</span><br><span class="line">        <span class="keyword">return</span> now</span><br></pre></td></tr></table></figure></li>
<li>DP不一定要数组，这里两个变量就够了，空间复杂度为$O(1)$<h2 id="200-Number-of-Islands-7行"><a href="#200-Number-of-Islands-7行" class="headerlink" title="200. Number of Islands 7行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/number-of-islands/">200. Number of Islands 7行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">numIslands</span>(<span class="params">self, grid</span>):</span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">sink</span>(<span class="params">i, j</span>):</span><br><span class="line">            <span class="keyword">if</span> <span class="number">0</span> &lt;= i &lt; <span class="built_in">len</span>(grid) <span class="keyword">and</span> <span class="number">0</span> &lt;= j &lt; <span class="built_in">len</span>(grid[i]) <span class="keyword">and</span> <span class="built_in">int</span>(grid[i][j]):</span><br><span class="line">                grid[i][j] = <span class="string">&#x27;0&#x27;</span></span><br><span class="line">                <span class="keyword">for</span> i, j <span class="keyword">in</span> <span class="built_in">zip</span>((i, i+<span class="number">1</span>, i, i-<span class="number">1</span>), (j+<span class="number">1</span>, j, j-<span class="number">1</span>, j)): sink(i, j)</span><br><span class="line">                <span class="keyword">return</span> <span class="number">1</span></span><br><span class="line">            <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sum</span>(sink(i, j) <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(grid)) <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(grid[i])))</span><br></pre></td></tr></table></figure></li>
<li>根据题意，我们可以把每一个陆地点当作树根，用 DFS 搜索四周的陆地并沉没它，那么这一整块的陆地都被沉没了，下次我们再遇到陆地点的时候就说明发现新大陆了<h2 id="202-Happy-Number-1行"><a href="#202-Happy-Number-1行" class="headerlink" title="202. Happy Number 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/happy-number/">202. Happy Number 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isHappy</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">return</span> self.isHappy(<span class="built_in">sum</span>(<span class="built_in">int</span>(i) ** <span class="number">2</span> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">str</span>(n))) <span class="keyword">if</span> n &gt; <span class="number">4</span> <span class="keyword">else</span> n == <span class="number">1</span></span><br></pre></td></tr></table></figure></li>
<li>不是快乐数的数称为不快乐数(unhappy number)，所有不快乐数的数位平方和计算，最后都会进入 <code>4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4</code> 的循环中</li>
<li>这个规律比较难想到的，正常解法是判断n是否会进入循环：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isHappy</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        seen = &#123;<span class="number">1</span>&#125;</span><br><span class="line">        <span class="keyword">while</span> n <span class="keyword">not</span> <span class="keyword">in</span> seen:</span><br><span class="line">            seen.add(n)</span><br><span class="line">            n = <span class="built_in">sum</span>(<span class="built_in">int</span>(i) ** <span class="number">2</span> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">str</span>(n))</span><br><span class="line">        <span class="keyword">return</span> n == <span class="number">1</span></span><br></pre></td></tr></table></figure>
<h2 id="203-Remove-Linked-List-Elements-2行"><a href="#203-Remove-Linked-List-Elements-2行" class="headerlink" title="203. Remove Linked List Elements 2行"></a><a href="">203. Remove Linked List Elements 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">removeElements</span>(<span class="params">self, head: ListNode, val: <span class="built_in">int</span></span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">if</span> head: head.<span class="built_in">next</span> = self.removeElements(head.<span class="built_in">next</span>, val)</span><br><span class="line">        <span class="keyword">return</span> head.<span class="built_in">next</span> <span class="keyword">if</span> head <span class="keyword">and</span> head.val == val <span class="keyword">else</span> head</span><br></pre></td></tr></table></figure></li>
<li>递归：每次都返回从当前位置算起第一个有效的节点或None<h2 id="205-Isomorphic-Strings-1行"><a href="#205-Isomorphic-Strings-1行" class="headerlink" title="205. Isomorphic Strings 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/isomorphic-strings/">205. Isomorphic Strings 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isIsomorphic</span>(<span class="params">self, s: <span class="built_in">str</span>, t: <span class="built_in">str</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">return</span> [*<span class="built_in">map</span>(s.index, s)] == [*<span class="built_in">map</span>(t.index, t)]</span><br></pre></td></tr></table></figure></li>
<li>同构代表两个字符串中每个位置上字符在自身第一次出现的索引相同<h2 id="206-Reverse-Linked-List-2行"><a href="#206-Reverse-Linked-List-2行" class="headerlink" title="206. Reverse Linked List 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/reverse-linked-list/">206. Reverse Linked List 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">reverseList</span>(<span class="params">self, head: ListNode, tail=<span class="literal">None</span></span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">if</span> head: head.<span class="built_in">next</span>, tail, head = tail, head, head.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">return</span> self.reverseList(head, tail) <span class="keyword">if</span> head <span class="keyword">else</span> tail</span><br></pre></td></tr></table></figure></li>
<li>递归解法</li>
<li>此解法为尾递归，即直接以递归返回值作为结果，一般编译器会做优化，避免多余的函数开栈操作，实现效果相当于迭代<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">reverseList</span>(<span class="params">self, head: ListNode</span>) -&gt; ListNode:</span><br><span class="line">        p = <span class="literal">None</span></span><br><span class="line">        <span class="keyword">while</span> head: head.<span class="built_in">next</span>, p, head = p, head, head.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">return</span> p</span><br></pre></td></tr></table></figure></li>
<li>迭代解法<h2 id="215-Kth-Largest-Element-in-an-Array-1行"><a href="#215-Kth-Largest-Element-in-an-Array-1行" class="headerlink" title="215. Kth Largest Element in an Array 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/kth-largest-element-in-an-array/">215. Kth Largest Element in an Array 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findKthLargest</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], k: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sorted</span>(nums)[-k]</span><br></pre></td></tr></table></figure></li>
<li>$O(N\log N)$调库</li>
<li>面试官一般不会接受以上答案的，可以参考下面这个$O(N)$的<code>quick-selection</code>，思路借鉴的<code>quick-sort</code>  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findKthLargest</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], k: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">	l = [x <span class="keyword">for</span> x <span class="keyword">in</span> nums <span class="keyword">if</span> x &gt; nums[<span class="number">0</span>]]</span><br><span class="line">	m = [x <span class="keyword">for</span> x <span class="keyword">in</span> nums <span class="keyword">if</span> x == nums[<span class="number">0</span>]]</span><br><span class="line">	r = [x <span class="keyword">for</span> x <span class="keyword">in</span> nums <span class="keyword">if</span> x &lt; nums[<span class="number">0</span>]]</span><br><span class="line">	f = self.findKthLargest</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> k &lt;= <span class="built_in">len</span>(l):</span><br><span class="line">	    <span class="keyword">return</span> f(l, k)</span><br><span class="line">	<span class="keyword">elif</span> k &lt;= <span class="built_in">len</span>(l) + <span class="built_in">len</span>(m):</span><br><span class="line">	    <span class="keyword">return</span> nums[<span class="number">0</span>]</span><br><span class="line">	<span class="keyword">return</span> f(r, k - <span class="built_in">len</span>(l) - <span class="built_in">len</span>(m))</span><br></pre></td></tr></table></figure>
<h2 id="217-Contains-Duplicate-1行"><a href="#217-Contains-Duplicate-1行" class="headerlink" title="217. Contains Duplicate 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/contains-duplicate/">217. Contains Duplicate 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">containsDuplicate</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">len</span>(nums) != <span class="built_in">len</span>(<span class="built_in">set</span>(nums))</span><br></pre></td></tr></table></figure>
<h2 id="219-Contains-Duplicate-II-4行"><a href="#219-Contains-Duplicate-II-4行" class="headerlink" title="219. Contains Duplicate II 4行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/contains-duplicate-ii/">219. Contains Duplicate II 4行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">containsNearbyDuplicate</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], k: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        r, d = k + <span class="number">1</span>, &#123;&#125;</span><br><span class="line">        <span class="keyword">for</span> i, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(nums):</span><br><span class="line">            r, d[n] = <span class="built_in">min</span>(r, i - d.get(n, -k - <span class="number">1</span>)), i</span><br><span class="line">        <span class="keyword">return</span> r &lt;= k</span><br></pre></td></tr></table></figure></li>
<li>本题题目有误，实际意思是找同数字最小间隔，若不超过 k 则满足条件</li>
<li>遍历列表，每次都比对最小间隔，并更新哈希表索引，当前位置往左的最小间隔一定是与上一次同数字出现的索引的距离<h2 id="225-Implement-Stack-using-Queues-6行"><a href="#225-Implement-Stack-using-Queues-6行" class="headerlink" title="225. Implement Stack using Queues 6行"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/implement-stack-using-queues/submissions/">225. Implement Stack using Queues 6行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">MyStack</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        self.q = collections.deque()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">push</span>(<span class="params">self, x</span>):</span><br><span class="line">        self.q.append(x)</span><br><span class="line">        <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(self.q) - <span class="number">1</span>): self.q.append(self.q.popleft())</span><br><span class="line">        </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pop</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> self.q.popleft()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">top</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> self.q[<span class="number">0</span>]</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">empty</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">not</span> <span class="built_in">len</span>(self.q)</span><br></pre></td></tr></table></figure></li>
<li>push 的时候把 x 放入队尾，然后遍历一遍原始队列元素，每次弹出之后加入队尾<h2 id="230-Kth-Smallest-Element-in-a-BST-3行"><a href="#230-Kth-Smallest-Element-in-a-BST-3行" class="headerlink" title="230. Kth Smallest Element in a BST 3行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/kth-smallest-element-in-a-bst/">230. Kth Smallest Element in a BST 3行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">kthSmallest</span>(<span class="params">self, root, k</span>):</span><br><span class="line">        <span class="keyword">from</span> itertools <span class="keyword">import</span> chain, islice</span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">gen</span>(<span class="params">x</span>): <span class="keyword">yield</span> <span class="keyword">from</span> chain(gen(x.left), [x.val], gen(x.right)) <span class="keyword">if</span> x <span class="keyword">else</span> ()</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">next</span>(islice(gen(root), k - <span class="number">1</span>, k))</span><br></pre></td></tr></table></figure></li>
<li>本题利用迭代器骚了一波，不太了解的话看这里 <a target="_blank" rel="noopener" href="https://blog.csdn.net/mieleizhi0522/article/details/82142856">【yield 推荐阅读博客】</a></li>
<li><code>chain</code> 函数可以组合多个迭代器，<code>islice</code> 函数对迭代器做切片操作</li>
<li>此题常规解法 <strong>中序遍历</strong> 还是需要了解下的  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode(object):</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">kthSmallest</span>(<span class="params">self, root, k</span>):</span><br><span class="line">	<span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">	:type root: TreeNode</span></span><br><span class="line"><span class="string">	:type k: int</span></span><br><span class="line"><span class="string">	:rtype: int</span></span><br><span class="line"><span class="string">	&quot;&quot;&quot;</span></span><br><span class="line">	res = []</span><br><span class="line">	self.visitNode(root, res)</span><br><span class="line">	<span class="keyword">return</span> res[k - <span class="number">1</span>]</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 中序遍历</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">visitNode</span>(<span class="params">self, root, res</span>):</span><br><span class="line">	<span class="keyword">if</span> root <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">	    <span class="keyword">return</span></span><br><span class="line">	self.visitNode(root.left, res)</span><br><span class="line">	res.append(root.val)</span><br><span class="line">	self.visitNode(root.right, res)</span><br></pre></td></tr></table></figure>
<h2 id="231-2的幂-1行"><a href="#231-2的幂-1行" class="headerlink" title="231. 2的幂 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/power-of-two/">231. 2的幂 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isPowerOfTwo</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">	<span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">	:type n: int</span></span><br><span class="line"><span class="string">	:rtype: bool</span></span><br><span class="line"><span class="string">	&quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> n &gt; <span class="number">0</span> <span class="keyword">and</span> n &amp; n - <span class="number">1</span> == <span class="number">0</span></span><br></pre></td></tr></table></figure></li>
<li>2 的幂的二进制形式最高位一定是1，其余为0</li>
<li>用常规思路也行  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isPowerOfTwo</span>(<span class="params">self, n</span>):</span><br><span class="line">	<span class="keyword">return</span> n &gt; <span class="number">0</span> <span class="keyword">and</span> <span class="number">2</span>**<span class="built_in">int</span>(math.log2(n)) == n</span><br></pre></td></tr></table></figure>
<h2 id="232-Implement-Queue-using-Stacks-13行"><a href="#232-Implement-Queue-using-Stacks-13行" class="headerlink" title="232. Implement Queue using Stacks 13行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/implement-queue-using-stacks/">232. Implement Queue using Stacks 13行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">MyQueue</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Initialize your data structure here.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.stack = []</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">push</span>(<span class="params">self, x: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Push element x to the back of queue.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.stack.append(x)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pop</span>(<span class="params">self</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Removes the element from in front of queue and returns that element.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        temp = []</span><br><span class="line">        <span class="keyword">while</span> self.stack: temp.append(self.stack.pop())</span><br><span class="line">        r = temp.pop()</span><br><span class="line">        <span class="keyword">while</span> temp: self.stack.append(temp.pop())</span><br><span class="line">        <span class="keyword">return</span> r</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">peek</span>(<span class="params">self</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Get the front element.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        temp = []</span><br><span class="line">        <span class="keyword">while</span> self.stack: temp.append(self.stack.pop())</span><br><span class="line">        r = temp[-<span class="number">1</span>]</span><br><span class="line">        <span class="keyword">while</span> temp: self.stack.append(temp.pop())</span><br><span class="line">        <span class="keyword">return</span> r</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">empty</span>(<span class="params">self</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Returns whether the queue is empty.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">not</span> self.stack</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your MyQueue object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = MyQueue()</span></span><br><span class="line"><span class="comment"># obj.push(x)</span></span><br><span class="line"><span class="comment"># param_2 = obj.pop()</span></span><br><span class="line"><span class="comment"># param_3 = obj.peek()</span></span><br><span class="line"><span class="comment"># param_4 = obj.empty()</span></span><br></pre></td></tr></table></figure></li>
<li>使用俩个栈来模拟队列，当需要取第一个元素的时候创建一个临时的栈temp，把栈里面的东西全部抽出来放进temp，完成操作后放回去<h2 id="234-Palindrome-Linked-List-3行"><a href="#234-Palindrome-Linked-List-3行" class="headerlink" title="234. Palindrome Linked List 3行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/palindrome-linked-list/">234. Palindrome Linked List 3行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isPalindrome</span>(<span class="params">self, head: ListNode</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">gen</span>(<span class="params">n</span>):</span><br><span class="line">            <span class="keyword">while</span> n: <span class="keyword">yield</span> n.val; n = n.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">return</span> [*gen(head)] == [*gen(head)][::-<span class="number">1</span>]</span><br></pre></td></tr></table></figure>
<h2 id="235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree-2行"><a href="#235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree-2行" class="headerlink" title="235. Lowest Common Ancestor of a Binary Search Tree 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/">235. Lowest Common Ancestor of a Binary Search Tree 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">lowestCommonAncestor</span>(<span class="params">self, root, p, q</span>):</span><br><span class="line">        <span class="keyword">while</span> (root.val - p.val) * (root.val - q.val) &gt; <span class="number">0</span>: root = (root.left, root.right)[p.val &gt; root.val]</span><br><span class="line">        <span class="keyword">return</span> root</span><br></pre></td></tr></table></figure></li>
<li>最近公共祖先的值一定介于<code>p</code>、<code>q</code>值之间（ 闭区间$[p, \;q]$ ）<h2 id="236-Lowest-Common-Ancestor-of-a-Binary-Tree-2行"><a href="#236-Lowest-Common-Ancestor-of-a-Binary-Tree-2行" class="headerlink" title="236. Lowest Common Ancestor of a Binary Tree 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/">236. Lowest Common Ancestor of a Binary Tree 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">lowestCommonAncestor</span>(<span class="params">self, root: <span class="string">&#x27;TreeNode&#x27;</span>, p: <span class="string">&#x27;TreeNode&#x27;</span>, q: <span class="string">&#x27;TreeNode&#x27;</span></span>) -&gt; <span class="string">&#x27;TreeNode&#x27;</span>:</span><br><span class="line">        l, r = <span class="built_in">map</span>(<span class="keyword">lambda</span> x: x <span class="keyword">and</span> self.lowestCommonAncestor(x, p, q), (root.left, root.right))</span><br><span class="line">        <span class="keyword">return</span> (root <span class="keyword">in</span> (p, q) <span class="keyword">or</span> l <span class="keyword">and</span> r) <span class="keyword">and</span> root <span class="keyword">or</span> l <span class="keyword">or</span> r</span><br></pre></td></tr></table></figure></li>
<li>递归全部节点，p 的祖先节点全部返回 p，q 的祖先节点全部返回 q，除非它同时是俩个节点的最近祖先，也就是 p，q 分别位于左右子树，那么返回自身</li>
<li>这思路用在<a target="_blank" rel="noopener" href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/">235</a>也行<h2 id="237-Delete-Node-in-a-Linked-List-1行"><a href="#237-Delete-Node-in-a-Linked-List-1行" class="headerlink" title="237. Delete Node in a Linked List 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/delete-node-in-a-linked-list/">237. Delete Node in a Linked List 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">deleteNode</span>(<span class="params">self, node</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        :type node: ListNode</span></span><br><span class="line"><span class="string">        :rtype: void Do not return anything, modify node in-place instead.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        node.val, node.<span class="built_in">next</span> = node.<span class="built_in">next</span>.val, node.<span class="built_in">next</span>.<span class="built_in">next</span></span><br></pre></td></tr></table></figure></li>
<li><code>node = node.next</code>是不行的，因为这里只是改了函数参数引用的对象，而原来传进来的 node 没有任何改变</li>
<li>详细说明下：如果Python的函数得到的参数是可变对象（比如list，set，这样的，内部属性可以改变的），那么我们实际得到的是这个对象的浅拷贝。比如这个函数刚刚开始的时候题目传进来一个参数node，我们设这个节点为A，那么实际上得到的参数node是一个对于A的一个浅拷贝，你可以想象node是一把钥匙，它可以打开真正的节点A的门，如果我们现在让<code>node = node.next</code>，那么我们只是换了钥匙，变成了打开 A.next 的门的对应的钥匙，因此链表没有被修改， A没有被修改，只是我们手里的钥匙变了。而如果我们直接写<code>node.val, node.next = node.next.val, node.next.next</code>，就相当于我们先用钥匙找到 A 的门，然后修改了 A 的属性，链表发生变化</li>
<li>此题考查python函数的传参形式为“传对象引用”，相当于浅拷贝（对于可变对象来说）<h2 id="238-Product-of-Array-Except-Self-5行"><a href="#238-Product-of-Array-Except-Self-5行" class="headerlink" title="238. Product of Array Except Self 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/product-of-array-except-self/">238. Product of Array Except Self 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">productExceptSelf</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        res, l, r = [<span class="number">1</span>] * <span class="built_in">len</span>(nums), <span class="number">1</span>, <span class="number">1</span></span><br><span class="line">        <span class="keyword">for</span> i, j <span class="keyword">in</span> <span class="built_in">zip</span>(<span class="built_in">range</span>(<span class="built_in">len</span>(nums)), <span class="built_in">reversed</span>(<span class="built_in">range</span>(<span class="built_in">len</span>(nums)))):</span><br><span class="line">            res[i], l = res[i] * l, l * nums[i]</span><br><span class="line">            res[j], r = res[j] * r, r * nums[j]</span><br><span class="line">        <span class="keyword">return</span> res</span><br></pre></td></tr></table></figure></li>
<li>$O(N)$双指针双向遍历<h2 id="240-Search-a-2D-Matrix-II-1行"><a href="#240-Search-a-2D-Matrix-II-1行" class="headerlink" title="240. Search a 2D Matrix II 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/search-a-2d-matrix-ii/">240. Search a 2D Matrix II 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">searchMatrix</span>(<span class="params">self, matrix, target</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        :type matrix: List[List[int]]</span></span><br><span class="line"><span class="string">        :type target: int</span></span><br><span class="line"><span class="string">        :rtype: bool</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">any</span>(target <span class="keyword">in</span> row <span class="keyword">for</span> row <span class="keyword">in</span> matrix)</span><br></pre></td></tr></table></figure></li>
<li>以下为 $O(m+n)$ 解法：  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">searchMatrix</span>(<span class="params">self, matrix, target</span>):</span><br><span class="line">	<span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">	:type matrix: List[List[int]]</span></span><br><span class="line"><span class="string">	:type target: int</span></span><br><span class="line"><span class="string">	:rtype: bool</span></span><br><span class="line"><span class="string">	&quot;&quot;&quot;</span></span><br><span class="line">	j = -<span class="number">1</span></span><br><span class="line">	<span class="keyword">for</span> row <span class="keyword">in</span> matrix:</span><br><span class="line">	    <span class="keyword">while</span> j &gt; -<span class="built_in">len</span>(row) <span class="keyword">and</span> row[j] &gt; target:</span><br><span class="line">		j -= <span class="number">1</span></span><br><span class="line">	    <span class="keyword">if</span> row <span class="keyword">and</span> row[j] == target:</span><br><span class="line">		<span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">	<span class="keyword">return</span> <span class="literal">False</span></span><br></pre></td></tr></table></figure>
<ul>
<li>从矩阵右上角开始，若值比 target 大则证明这一列的值都比 target 大，继续搜索前面的列；若比 target 小说明 target 可能在后面的行中，进入下一行<h2 id="258-Add-Digits-1行"><a href="#258-Add-Digits-1行" class="headerlink" title="258. Add Digits 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/add-digits/">258. Add Digits 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">addDigits</span>(<span class="params">self, num: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> num % <span class="number">9</span> <span class="keyword">or</span> <span class="number">9</span> * <span class="built_in">bool</span>(num)</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li>$O(1)$ 数学推理：设某个数字的字符串表示为<code>&#39;abc&#39;</code>，则这个数字代表<code>a*100 + b*10 + c</code>，转换后成为<code>a + b + c</code>，可见每次转换相当于把原数字减去<code>a*99 + b*9 = 9 * (a*11 + b)</code>，可以推出只要高于个位的位置上有数字，算法就会减去一个小于原数字的9的倍数，这就相当于<code>数字 % 9</code>。但<code>9 % 9 = 0</code>，而 9 本身就没有十位，因此需要考虑原数字是 0 或 9 的倍数的特殊情况</li>
<li>首先计算<code>num % 9</code>，若结果为 0 则考虑<code>num</code>本身是否为 0，若不为 0 返回 9<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">addDigits</span>(<span class="params">self, num: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">while</span> num &gt; <span class="number">9</span>:</span><br><span class="line">            num = <span class="built_in">eval</span>(<span class="string">&#x27;+&#x27;</span>.join(n <span class="keyword">for</span> n <span class="keyword">in</span> <span class="built_in">str</span>(num)))</span><br><span class="line">        <span class="keyword">return</span> num</span><br></pre></td></tr></table></figure></li>
<li>循环判断<h2 id="268-Missing-Number-1行"><a href="#268-Missing-Number-1行" class="headerlink" title="268. Missing Number 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/missing-number/">268. Missing Number 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">missingNumber</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sum</span>(<span class="built_in">range</span>(<span class="built_in">len</span>(nums) + <span class="number">1</span>)) - <span class="built_in">sum</span>(nums)</span><br></pre></td></tr></table></figure></li>
<li>$O(N)$时间，$O(1)$空间（迭代器）<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">missingNumber</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">int</span>(<span class="built_in">len</span>(nums) * (<span class="built_in">len</span>(nums) + <span class="number">1</span>) / <span class="number">2</span> - <span class="built_in">sum</span>(nums))</span><br></pre></td></tr></table></figure></li>
<li>等差数列求和公式，$O(1)$空间<h2 id="278-First-Bad-Version-2行"><a href="#278-First-Bad-Version-2行" class="headerlink" title="278. First Bad Version 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/first-bad-version/">278. First Bad Version 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># The isBadVersion API is already defined for you.</span></span><br><span class="line"><span class="comment"># @param version, an integer</span></span><br><span class="line"><span class="comment"># @return a bool</span></span><br><span class="line"><span class="comment"># def isBadVersion(version):</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">firstBadVersion</span>(<span class="params">self, n</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        :type n: int</span></span><br><span class="line"><span class="string">        :rtype: int</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.__class__.__getitem__ = <span class="keyword">lambda</span> self, x: isBadVersion(x)</span><br><span class="line">        <span class="keyword">return</span> bisect.bisect_left(self, <span class="literal">True</span>, <span class="number">1</span>, n)</span><br></pre></td></tr></table></figure></li>
<li>改造当前类的魔法方法<code>getitem</code>以使用内置函数</li>
<li>复现二分搜索解法如下：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># The isBadVersion API is already defined for you.</span></span><br><span class="line"><span class="comment"># @param version, an integer</span></span><br><span class="line"><span class="comment"># @return a bool</span></span><br><span class="line"><span class="comment"># def isBadVersion(version):</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">firstBadVersion</span>(<span class="params">self, n</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        :type n: int</span></span><br><span class="line"><span class="string">        :rtype: int</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        l, h = <span class="number">1</span>, n</span><br><span class="line">        <span class="keyword">while</span> l &lt;= h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> isBadVersion(m) &gt; m * isBadVersion(m - <span class="number">1</span>):</span><br><span class="line">                <span class="keyword">return</span> m</span><br><span class="line">            <span class="keyword">elif</span> isBadVersion(m):</span><br><span class="line">                h = m - <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = m + <span class="number">1</span></span><br></pre></td></tr></table></figure></li>
<li>本题二分搜索中判断返回的条件为 当前版本为<code>True</code>且（当前索引为0 或 左边的版本为<code>False</code>）</li>
<li><code>m *</code> 的作用是避免 <code>m - 1</code> 为负数，如果 m 为 0，则代表左边没有版本，只需判断当前版本是否为 <code>True</code></li>
<li><code>True &gt; False</code> 或 0<h2 id="279-Perfect-Squares-4行"><a href="#279-Perfect-Squares-4行" class="headerlink" title="279. Perfect Squares 4行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/perfect-squares/">279. Perfect Squares 4行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">numSquares</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        dp = [<span class="number">0</span>]</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, n+<span class="number">1</span>):</span><br><span class="line">            dp.append(<span class="built_in">min</span>(dp[-j*j] <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, <span class="number">1</span> + <span class="built_in">int</span>(i**<span class="number">0.5</span>))) + <span class="number">1</span>)</span><br><span class="line">        <span class="keyword">return</span> dp[-<span class="number">1</span>]</span><br></pre></td></tr></table></figure></li>
<li>dp方程：总和为 n 的最小完全平方数个数 = min(总和为 (n - 某个完全平方数) 的最小完全平方数个数) + 1</li>
<li>中文版力扣这题用dp会超时，可以<a href="#279-完全平方数">使用bfs</a>，或者<strong>拉格朗日四平方数和定理</strong> 😎：任何一个正整数都可以表示成不超过四个整数的平方之和。 推论：满足四数平方和定理的数n（四个整数的情况），必定满足 $n=4^{a(8b+7)}$<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">numSquares</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">while</span> n % <span class="number">4</span> == <span class="number">0</span>:</span><br><span class="line">            n /= <span class="number">4</span></span><br><span class="line">        <span class="keyword">if</span> n % <span class="number">8</span> == <span class="number">7</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="number">4</span></span><br><span class="line">        </span><br><span class="line">        a = <span class="number">0</span></span><br><span class="line">        <span class="keyword">while</span> a**<span class="number">2</span> &lt;= n:</span><br><span class="line">            b = <span class="built_in">int</span>((n - a**<span class="number">2</span>)**<span class="number">0.5</span>) </span><br><span class="line">            <span class="keyword">if</span> a**<span class="number">2</span> + b**<span class="number">2</span> == n:</span><br><span class="line">                <span class="keyword">return</span> <span class="built_in">bool</span>(a) + <span class="built_in">bool</span>(b) </span><br><span class="line">            a += <span class="number">1</span></span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> <span class="number">3</span></span><br></pre></td></tr></table></figure>
<h2 id="283-Move-Zeroes-1行"><a href="#283-Move-Zeroes-1行" class="headerlink" title="283. Move Zeroes 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/move-zeroes/">283. Move Zeroes 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">moveZeroes</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Do not return anything, modify nums in-place instead.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        nums.sort(key=<span class="built_in">bool</span>, reverse=<span class="literal">True</span>)</span><br></pre></td></tr></table></figure></li>
<li><code>sort</code> 时间复杂度为$O(N\log N)$, 直接遍历可以达到 $O(N)$<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">moveZeroes</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Do not return anything, modify nums in-place instead.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        i = <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> i, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(<span class="built_in">filter</span>(<span class="keyword">lambda</span> x: x, nums)):</span><br><span class="line">            nums[i] = n</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(i + <span class="number">1</span>, <span class="built_in">len</span>(nums)):</span><br><span class="line">            nums[i] = <span class="number">0</span></span><br></pre></td></tr></table></figure></li>
<li>直接使用 <code>filter</code> 迭代器可以避免交换操作，思路更简单<h2 id="287-Find-the-Duplicate-Number-2行"><a href="#287-Find-the-Duplicate-Number-2行" class="headerlink" title="287. Find the Duplicate Number 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/find-the-duplicate-number/">287. Find the Duplicate Number 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findDuplicate</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        self.__class__.__getitem__ = <span class="keyword">lambda</span> sef, m: <span class="built_in">sum</span>(n &lt;= m <span class="keyword">for</span> n <span class="keyword">in</span> nums) &gt; m</span><br><span class="line">        <span class="keyword">return</span> bisect.bisect_left(self, <span class="literal">True</span>, <span class="number">1</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span>)</span><br></pre></td></tr></table></figure></li>
<li>本题可用二分查找，整个算法时间复杂度为 $O(N\log N)$，由题意可知搜索范围在 1 到 n 之间，那么如何缩小范围？只需判断数组中不超过中间数 m 的元素数量是否大于 m 即可，若大于，则表示范围 1 到 m 内肯定包含重复的数字</li>
<li>搜索范围为 [1, n]，向左（包括target）搜索的条件为：不大于 n 的数字在 nums 存在超过 m 个，即搜索范围可以被缩小为 [1, m]<h2 id="292-Nim-Game-1行"><a href="#292-Nim-Game-1行" class="headerlink" title="292. Nim Game 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/nim-game/">292. Nim Game 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">canWinNim</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">bool</span>(n % <span class="number">4</span>)</span><br></pre></td></tr></table></figure></li>
<li>只要轮到你的时候剩余石头数量不是 4 的倍数都是完胜，因为你有办法使得每次轮到对方的时候剩余石头数量都为 4 的倍数<h2 id="326-Power-of-Three-1行"><a href="#326-Power-of-Three-1行" class="headerlink" title="326. Power of Three 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/power-of-three/">326. Power of Three 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isPowerOfThree</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">return</span> n &gt; <span class="number">0</span> <span class="keyword">and</span> <span class="number">3</span> ** <span class="built_in">round</span>(math.log(n, <span class="number">3</span>)) == n</span><br></pre></td></tr></table></figure></li>
<li><code>math.log</code> 函数得到的数据可能不够精确，可以使用 <code>round</code> 取整<h2 id="328-Odd-Even-Linked-List-6行"><a href="#328-Odd-Even-Linked-List-6行" class="headerlink" title="328. Odd Even Linked List 6行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/odd-even-linked-list/">328. Odd Even Linked List 6行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">oddEvenList</span>(<span class="params">self, head: ListNode</span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> head <span class="keyword">or</span> <span class="keyword">not</span> head.<span class="built_in">next</span>: <span class="keyword">return</span> head</span><br><span class="line">        r, odd, p, head = head, head, head.<span class="built_in">next</span>, head.<span class="built_in">next</span>.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">while</span> head:</span><br><span class="line">            odd.<span class="built_in">next</span>, head.<span class="built_in">next</span>, p.<span class="built_in">next</span> = head, odd.<span class="built_in">next</span>, head.<span class="built_in">next</span></span><br><span class="line">            p, odd, head = p.<span class="built_in">next</span>, head, p.<span class="built_in">next</span> <span class="keyword">and</span> p.<span class="built_in">next</span>.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>odd 记录上一个奇数位节点，p 记录前一个节点</li>
<li>从第3个位置开始循环，每次都把当前节点接到 odd 后面，然后跳到下一个奇数位节点继续循环<h2 id="342-Power-of-Four-1行"><a href="#342-Power-of-Four-1行" class="headerlink" title="342. Power of Four 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/power-of-four/">342. Power of Four 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isPowerOfFour</span>(<span class="params">self, num: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">return</span> num &gt; <span class="number">0</span> <span class="keyword">and</span> <span class="keyword">not</span> math.log(num, <span class="number">4</span>) % <span class="number">1</span></span><br></pre></td></tr></table></figure></li>
<li>采用 log 运算，若结果为整数则 <code>num</code> 为 4 的幂</li>
<li>整数 % 1 为 0<h2 id="344-Reverse-String-1行"><a href="#344-Reverse-String-1行" class="headerlink" title="344. Reverse String 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/reverse-string/">344. Reverse String 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">reverseString</span>(<span class="params">self, s: <span class="type">List</span>[<span class="built_in">str</span>]</span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Do not return anything, modify s in-place instead.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        s.reverse()</span><br></pre></td></tr></table></figure>
<h2 id="345-Reverse-Vowels-of-a-String-2行"><a href="#345-Reverse-Vowels-of-a-String-2行" class="headerlink" title="345. Reverse Vowels of a String 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/reverse-vowels-of-a-string/">345. Reverse Vowels of a String 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">reverseVowels</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        vowels = re.findall(<span class="string">&#x27;(?i)[aeiou]&#x27;</span>, s)</span><br><span class="line">        <span class="keyword">return</span> re.sub(<span class="string">&#x27;(?i)[aeiou]&#x27;</span>, <span class="keyword">lambda</span> m: vowels.pop(), s)</span><br></pre></td></tr></table></figure></li>
<li>遍历俩次，第一次找出元音字母放进 stack，第二次每遇到一个就把之前的栈顶替换进来<h2 id="347-Top-K-Frequent-Elements-1行"><a href="#347-Top-K-Frequent-Elements-1行" class="headerlink" title="347. Top K Frequent Elements 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/top-k-frequent-elements/">347. Top K Frequent Elements 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">topKFrequent</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], k: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> [*<span class="built_in">next</span>(<span class="built_in">zip</span>(*collections.Counter(nums).most_common(k)))]</span><br></pre></td></tr></table></figure></li>
<li>Counter类的目的是用来跟踪值出现的次数。它是一个无序的容器类型，以字典的键值对形式存储，其中元素作为key，其计数作为value</li>
<li>关于 Counter，更多详细内容可参考 <a target="_blank" rel="noopener" href="https://www.cnblogs.com/nisen/p/6052895.html">这里</a></li>
<li>非内置解法：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">topKFrequent</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], k: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        d = &#123;n: <span class="number">0</span> <span class="keyword">for</span> n <span class="keyword">in</span> nums&#125;</span><br><span class="line">        <span class="keyword">for</span> n <span class="keyword">in</span> nums:</span><br><span class="line">            d[n] += <span class="number">1</span></span><br><span class="line">        </span><br><span class="line">        r = []</span><br><span class="line">        <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(k):</span><br><span class="line">            n = <span class="built_in">max</span>(d, key=d.get)</span><br><span class="line">            r.append(n)</span><br><span class="line">            d[n] = -<span class="number">1</span></span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure>
<h2 id="349-Intersection-of-Two-Arrays-1行"><a href="#349-Intersection-of-Two-Arrays-1行" class="headerlink" title="349. Intersection of Two Arrays 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/intersection-of-two-arrays/">349. Intersection of Two Arrays 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">intersection</span>(<span class="params">self, nums1: <span class="type">List</span>[<span class="built_in">int</span>], nums2: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> [*<span class="built_in">set</span>(nums1) &amp; <span class="built_in">set</span>(nums2)]</span><br></pre></td></tr></table></figure></li>
<li>经过 set 之后，重复的元素被删除</li>
<li>与运算对于集合来说就是求交集<h2 id="350-Intersection-of-Two-Arrays-II-1行"><a href="#350-Intersection-of-Two-Arrays-II-1行" class="headerlink" title="350. Intersection of Two Arrays II 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/intersection-of-two-arrays-ii/">350. Intersection of Two Arrays II 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">intersect</span>(<span class="params">self, nums1: <span class="type">List</span>[<span class="built_in">int</span>], nums2: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> [*(collections.Counter(nums1) &amp; collections.Counter(nums2)).elements()]</span><br></pre></td></tr></table></figure></li>
<li>对于两个 Counter 对象，与操作意味着取两者都有的key, value取小的那一个</li>
<li>参考：<a target="_blank" rel="noopener" href="https://www.cnblogs.com/nisen/p/6052895.html">Python Counter 计数工具</a><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">intersect</span>(<span class="params">self, nums1: <span class="type">List</span>[<span class="built_in">int</span>], nums2: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        nums1.sort()</span><br><span class="line">        nums2.sort()</span><br><span class="line">        r = []</span><br><span class="line">        i = j = <span class="number">0</span></span><br><span class="line">        <span class="keyword">while</span> i &lt; <span class="built_in">len</span>(nums1) <span class="keyword">and</span> j &lt; <span class="built_in">len</span>(nums2):</span><br><span class="line">            <span class="keyword">if</span> nums1[i] == nums2[j]:</span><br><span class="line">                r.append(nums1[i])</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">                j += <span class="number">1</span></span><br><span class="line">            <span class="keyword">elif</span> nums1[i] &lt; nums2[j]:</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                j += <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>进阶解法 ↑</li>
<li>使用双指针将两个列表中共同的元素抠下来，因为已经排序，所以遇到不同元素时数值小的那个列表的指针向前移动<h2 id="367-Valid-Perfect-Square-4行"><a href="#367-Valid-Perfect-Square-4行" class="headerlink" title="367. Valid Perfect Square 4行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/valid-perfect-square/">367. Valid Perfect Square 4行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isPerfectSquare</span>(<span class="params">self, num: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        r = num</span><br><span class="line">        <span class="keyword">while</span> r * r &gt; num:</span><br><span class="line">            r = (r + num / r) // <span class="number">2</span></span><br><span class="line">        <span class="keyword">return</span> r * r == num</span><br></pre></td></tr></table></figure></li>
<li>基本不等式$\frac{a+b}{2} \ge \sqrt{ab}$ 推导自 $(a-b)^2 \ge 0$ → $a^2 + b^2 \ge 2ab$ → $\frac{a+b}{2} \ge \sqrt{ab}$（换元），注意 $a&gt;0$ 且 $b&gt;0$</li>
<li>$\frac { r+ \frac{num}{r}}{2} \ge \sqrt{num}$ 而 $r &gt; \frac{num}{r}$ 保证每次迭代 r 在不断减小,而<code>//</code>的存在保证最接近的时候能够逃离循环体<h2 id="387-First-Unique-Character-in-a-String-2行"><a href="#387-First-Unique-Character-in-a-String-2行" class="headerlink" title="387. First Unique Character in a String 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/first-unique-character-in-a-string/">387. First Unique Character in a String 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">firstUniqChar</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        d = &#123;c: s.count(c) <span class="keyword">for</span> c <span class="keyword">in</span> <span class="built_in">set</span>(s)&#125;</span><br><span class="line">        <span class="keyword">return</span> ([i <span class="keyword">for</span> i, c <span class="keyword">in</span> <span class="built_in">enumerate</span>(s) <span class="keyword">if</span> d[c] == <span class="number">1</span>] + [-<span class="number">1</span>])[<span class="number">0</span>]</span><br></pre></td></tr></table></figure></li>
<li>首先用字典 d 储存｛字符：出现次数｝，注意这里的字符来自 set，为了避免重复操作，防止TLE</li>
<li>用 list 记录 s 中出现次数为 1 的字符的索引</li>
<li>返回 list 第一个元素，如果原来的 s 中不存在出现次数为 1 的字符，则会返回后面添加的 [-1] 作为第一个元素<h2 id="389-Find-the-Difference-1行"><a href="#389-Find-the-Difference-1行" class="headerlink" title="389. Find the Difference 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/find-the-difference/">389. Find the Difference 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findTheDifference</span>(<span class="params">self, s: <span class="built_in">str</span>, t: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">chr</span>(<span class="built_in">sum</span>(<span class="built_in">map</span>(<span class="built_in">ord</span>, t)) - <span class="built_in">sum</span>(<span class="built_in">map</span>(<span class="built_in">ord</span>, s)))</span><br></pre></td></tr></table></figure></li>
<li>每一个字符都对应一个 ASCII 数字，那么那个不同的数字的 ASCII 码就等于 t 的所有字符码之和 - s 的</li>
<li>ord 函数将单个字符转换为 ASCII 码， chr相反<h2 id="394-Decode-String-14行"><a href="#394-Decode-String-14行" class="headerlink" title="394. Decode String 14行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/decode-string/">394. Decode String 14行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">decodeString</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        stack = [[<span class="string">&#x27;&#x27;</span>, <span class="number">1</span>, <span class="string">&#x27;&#x27;</span>]]</span><br><span class="line">        a = n = <span class="string">&#x27;&#x27;</span></span><br><span class="line">        <span class="keyword">for</span> c <span class="keyword">in</span> s:</span><br><span class="line">            <span class="keyword">if</span> c.isalpha():</span><br><span class="line">                a += c</span><br><span class="line">            <span class="keyword">elif</span> c.isdigit():</span><br><span class="line">                n += c</span><br><span class="line">            <span class="keyword">elif</span> c == <span class="string">&#x27;[&#x27;</span>:</span><br><span class="line">                stack.append([a, <span class="built_in">int</span>(n), <span class="string">&#x27;&#x27;</span>])</span><br><span class="line">                a = n = <span class="string">&#x27;&#x27;</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                p, t, b = stack.pop()</span><br><span class="line">                stack[-<span class="number">1</span>][-<span class="number">1</span>] += p + t * (b + a)</span><br><span class="line">                a = <span class="string">&#x27;&#x27;</span></span><br><span class="line">        <span class="keyword">return</span> stack.pop()[-<span class="number">1</span>] + a</span><br></pre></td></tr></table></figure></li>
<li>用 stack 记录（[]之前的字母，翻倍次数，翻倍内容）<h2 id="412-Fizz-Buzz-1行"><a href="#412-Fizz-Buzz-1行" class="headerlink" title="412. Fizz Buzz 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/fizz-buzz/">412. Fizz Buzz 1行</a></h2></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">fizzBuzz</span>(<span class="params">self, n</span>):</span><br><span class="line">        <span class="keyword">return</span> [<span class="string">&#x27;Fizz&#x27;</span> * (<span class="keyword">not</span> i % <span class="number">3</span>) + <span class="string">&#x27;Buzz&#x27;</span> * (<span class="keyword">not</span> i % <span class="number">5</span>) <span class="keyword">or</span> <span class="built_in">str</span>(i) <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, n+<span class="number">1</span>)]</span><br></pre></td></tr></table></figure>
<ul>
<li>7 or 8 = 7</li>
<li>0 or 8 = 8<h2 id="414-Third-Maximum-Number-3行"><a href="#414-Third-Maximum-Number-3行" class="headerlink" title="414. Third Maximum Number 3行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/third-maximum-number/">414. Third Maximum Number 3行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">thirdMax</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        nums = <span class="built_in">set</span>(nums)</span><br><span class="line">        <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>((<span class="number">2</span>, <span class="number">0</span>)[<span class="built_in">len</span>(nums) &lt; <span class="number">3</span>]): nums.remove(<span class="built_in">max</span>(nums))</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">max</span>(nums)</span><br></pre></td></tr></table></figure>
<h2 id="430-Flatten-a-Multilevel-Doubly-Linked-List-5行"><a href="#430-Flatten-a-Multilevel-Doubly-Linked-List-5行" class="headerlink" title="430. Flatten a Multilevel Doubly Linked List 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/">430. Flatten a Multilevel Doubly Linked List 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string"># Definition for a Node.</span></span><br><span class="line"><span class="string">class Node:</span></span><br><span class="line"><span class="string">    def __init__(self, val, prev, next, child):</span></span><br><span class="line"><span class="string">        self.val = val</span></span><br><span class="line"><span class="string">        self.prev = prev</span></span><br><span class="line"><span class="string">        self.next = next</span></span><br><span class="line"><span class="string">        self.child = child</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">from</span> itertools <span class="keyword">import</span> chain</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">flatten</span>(<span class="params">self, head: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="string">&#x27;Node&#x27;</span>:</span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">gen</span>(<span class="params">n</span>): <span class="keyword">yield</span> <span class="keyword">from</span> chain([n], gen(n.child), gen(n.<span class="built_in">next</span>)) <span class="keyword">if</span> n <span class="keyword">else</span> ()</span><br><span class="line">        iters = gen(head); p = head <span class="keyword">and</span> <span class="built_in">next</span>(iters)</span><br><span class="line">        <span class="keyword">for</span> n <span class="keyword">in</span> iters: p.<span class="built_in">next</span>, n.prev, p.child, n.child, p = n, p, <span class="literal">None</span>, <span class="literal">None</span>, n</span><br><span class="line">        <span class="keyword">return</span> head</span><br></pre></td></tr></table></figure></li>
<li>使用迭代器按顺序输出所有节点，然后连接<h2 id="448-Find-All-Numbers-Disappeared-in-an-Array-1行"><a href="#448-Find-All-Numbers-Disappeared-in-an-Array-1行" class="headerlink" title="448. Find All Numbers Disappeared in an Array 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/">448. Find All Numbers Disappeared in an Array 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findDisappearedNumbers</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        s = <span class="built_in">set</span>(nums)</span><br><span class="line">        <span class="keyword">return</span> [i <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, <span class="built_in">len</span>(nums) + <span class="number">1</span>) <span class="keyword">if</span> i <span class="keyword">not</span> <span class="keyword">in</span> s]</span><br></pre></td></tr></table></figure></li>
<li><code>set</code> 的内部实现为 <code>dict</code>，<code>in</code> 操作时间复杂度为 $O(1)$</li>
<li>应题目进阶要求，以下解为 $O(N)$ 时间效率，无额外空间（除了返回数组和中间变量）  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findDisappearedNumbers</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">	<span class="keyword">for</span> n <span class="keyword">in</span> nums:</span><br><span class="line">	    nums[<span class="built_in">abs</span>(n) - <span class="number">1</span>] = -<span class="built_in">abs</span>(nums[<span class="built_in">abs</span>(n) - <span class="number">1</span>])</span><br><span class="line">	<span class="keyword">return</span> [i + <span class="number">1</span> <span class="keyword">for</span> i, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(nums) <span class="keyword">if</span> n &gt; <span class="number">0</span>]</span><br></pre></td></tr></table></figure>
<ul>
<li>此解实际上是利用索引把数组自身当作哈希表处理</li>
<li>将 nums 中所有正数作为索引i，置 nums[i] 为负值。那么，仍为正数的位置即为（未出现过）消失的数字<ul>
<li>原始数组：<code>[4,3,2,7,8,2,3,1]</code></li>
<li>重置后为：<code>[-4,-3,-2,-7,8,2,-3,-1]</code></li>
<li>结论：[8,2] 分别对应的index为[5,6]（消失的数字）<h2 id="454-4Sum-II-2行"><a href="#454-4Sum-II-2行" class="headerlink" title="454. 4Sum II 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/4sum-ii/">454. 4Sum II 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">fourSumCount</span>(<span class="params">self, A: <span class="type">List</span>[<span class="built_in">int</span>], B: <span class="type">List</span>[<span class="built_in">int</span>], C: <span class="type">List</span>[<span class="built_in">int</span>], D: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        dic = collections.Counter(a + b <span class="keyword">for</span> a <span class="keyword">in</span> A <span class="keyword">for</span> b <span class="keyword">in</span> B)</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sum</span>(dic.get(- c - d, <span class="number">0</span>) <span class="keyword">for</span> c <span class="keyword">in</span> C <span class="keyword">for</span> d <span class="keyword">in</span> D)</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
</ul>
</li>
<li>思路同第一题 TWO SUM 的 $O(N)$ 字典解法，记录需要的值<h2 id="461-Hamming-Distance-1行"><a href="#461-Hamming-Distance-1行" class="headerlink" title="461. Hamming Distance 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/hamming-distance/">461. Hamming Distance 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">hammingDistance</span>(<span class="params">self, x: <span class="built_in">int</span>, y: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">bin</span>(x ^ y).count(<span class="string">&#x27;1&#x27;</span>)</span><br></pre></td></tr></table></figure>
<h2 id="485-Max-Consecutive-Ones-1行"><a href="#485-Max-Consecutive-Ones-1行" class="headerlink" title="485. Max Consecutive Ones 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/max-consecutive-ones/">485. Max Consecutive Ones 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findMaxConsecutiveOnes</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">len</span>(<span class="built_in">max</span>(<span class="string">&#x27;&#x27;</span>.join(<span class="built_in">map</span>(<span class="built_in">str</span>, nums)).split(<span class="string">&#x27;0&#x27;</span>)))</span><br></pre></td></tr></table></figure></li>
<li>变成字符串然后用”0”去切分然后比子串长度<h2 id="494-Target-Sum-5行"><a href="#494-Target-Sum-5行" class="headerlink" title="494. Target Sum 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/target-sum/">494. Target Sum 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findTargetSumWays</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], S: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">dfs</span>(<span class="params">cur, i, d = &#123;&#125;</span>):</span><br><span class="line">            <span class="keyword">if</span> i &lt; <span class="built_in">len</span>(nums) <span class="keyword">and</span> (i, cur) <span class="keyword">not</span> <span class="keyword">in</span> d: <span class="comment"># 搜索周围节点</span></span><br><span class="line">                d[(i, cur)] = dfs(cur + nums[i], i + <span class="number">1</span>) + dfs(cur - nums[i], i + <span class="number">1</span>)</span><br><span class="line">            <span class="keyword">return</span> d.get((i, cur), <span class="built_in">int</span>(cur == S))</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> dfs(<span class="number">0</span>, <span class="number">0</span>)</span><br></pre></td></tr></table></figure></li>
<li>dfs遍历所有可能结果，以当前位置 i 和当前总和 cur 为根节点，以下一位数字的加减为邻域扩散搜索</li>
<li>利用 d 构造记忆，以便剪枝（搜索过程中遇到相同位置和相同cur值时返回值应该相同）</li>
<li>dfs中 d 参数传的是引用，所以只有第一次会采用默认值 {}<h2 id="495-Teemo-Attacking"><a href="#495-Teemo-Attacking" class="headerlink" title="495. Teemo Attacking"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/teemo-attacking/">495. Teemo Attacking</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findPoisonedDuration</span>(<span class="params">self, t: <span class="type">List</span>[<span class="built_in">int</span>], d: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">len</span>(t) <span class="keyword">and</span> <span class="built_in">sum</span>(<span class="built_in">min</span>(t[i] - t[i-<span class="number">1</span>], d) <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, <span class="built_in">len</span>(t))) + d</span><br></pre></td></tr></table></figure></li>
<li>总时间 = 所有间隔时间的总和，每一次的间隔时间 = min(下次发射时间 - 这次发射时间，duration)<h2 id="498-Diagonal-Traverse-5行"><a href="#498-Diagonal-Traverse-5行" class="headerlink" title="498. Diagonal Traverse 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/diagonal-traverse/">498. Diagonal Traverse 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findDiagonalOrder</span>(<span class="params">self, matrix: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        m, n, r = <span class="built_in">len</span>(matrix), <span class="built_in">len</span>(matrix) <span class="keyword">and</span> <span class="built_in">len</span>(matrix[<span class="number">0</span>]), []</span><br><span class="line">        <span class="keyword">for</span> l <span class="keyword">in</span> <span class="built_in">range</span>(m + n - <span class="number">1</span>):</span><br><span class="line">            temp = [matrix[i][l - i] <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">max</span>(<span class="number">0</span>, l+<span class="number">1</span> - n), <span class="built_in">min</span>(l+<span class="number">1</span>, m))]</span><br><span class="line">            r += temp <span class="keyword">if</span> l % <span class="number">2</span> <span class="keyword">else</span> temp[::-<span class="number">1</span>]</span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>0 and 0 答案是 0，此处避免 matrix 为 [] 时导致报错</li>
<li>按照从右上角到左下角的顺序遍历 matrix 的所有对角线并放入列表 temp</li>
<li>如果 对角线元素个数 是偶数则应该把 temp 反转</li>
<li>把 temp 加入结果 r<h2 id="507-Perfect-Number"><a href="#507-Perfect-Number" class="headerlink" title="507. Perfect Number"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/perfect-number/">507. Perfect Number</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">checkPerfectNumber</span>(<span class="params">self, num: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">return</span> num <span class="keyword">in</span> (<span class="number">6</span>, <span class="number">28</span>, <span class="number">496</span>, <span class="number">8128</span>, <span class="number">33550336</span>, <span class="number">8589869056</span>, <span class="number">137438691328</span>, <span class="number">2305843008139952128</span>)</span><br></pre></td></tr></table></figure></li>
<li>题目中给出了解的范围，且解的个数是固定的，因此可以提前计算出所有解<h2 id="557-Reverse-Words-in-a-String-III-1行"><a href="#557-Reverse-Words-in-a-String-III-1行" class="headerlink" title="557. Reverse Words in a String III 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/reverse-words-in-a-string-iii/">557. Reverse Words in a String III 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">reverseWords</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27; &#x27;</span>.join(s.split(<span class="string">&#x27; &#x27;</span>)[::-<span class="number">1</span>])[::-<span class="number">1</span>]</span><br></pre></td></tr></table></figure>
<h2 id="561-Array-Partition-I-1行"><a href="#561-Array-Partition-I-1行" class="headerlink" title="561. Array Partition I 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/array-partition-i/">561. Array Partition I 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">arrayPairSum</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sum</span>(<span class="built_in">sorted</span>(nums)[::<span class="number">2</span>])</span><br></pre></td></tr></table></figure>
<h2 id="575-Distribute-Candies-1行"><a href="#575-Distribute-Candies-1行" class="headerlink" title="575. Distribute Candies 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/distribute-candies/">575. Distribute Candies 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">distributeCandies</span>(<span class="params">self, candies: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">min</span>(<span class="built_in">len</span>(<span class="built_in">set</span>(candies)), <span class="built_in">len</span>(candies) // <span class="number">2</span>)</span><br></pre></td></tr></table></figure></li>
<li>姐姐优先拿不同种类的糖果<h2 id="581-Shortest-Unsorted-Continuous-Subarray-2行"><a href="#581-Shortest-Unsorted-Continuous-Subarray-2行" class="headerlink" title="581. Shortest Unsorted Continuous Subarray 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/shortest-unsorted-continuous-subarray/">581. Shortest Unsorted Continuous Subarray 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findUnsortedSubarray</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        diff = [i <span class="keyword">for</span> i, (a, b) <span class="keyword">in</span> <span class="built_in">enumerate</span>(<span class="built_in">zip</span>(nums, <span class="built_in">sorted</span>(nums))) <span class="keyword">if</span> a != b]</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">len</span>(diff) <span class="keyword">and</span> <span class="built_in">max</span>(diff) - <span class="built_in">min</span>(diff) + <span class="number">1</span></span><br></pre></td></tr></table></figure></li>
<li>获取所有当前数组与排序后数组具有不同数值的索引，最右边的索引 - 最左边的 + 1 就是结果<h2 id="589-N-ary-Tree-Preorder-Traversal-1行"><a href="#589-N-ary-Tree-Preorder-Traversal-1行" class="headerlink" title="589. N-ary Tree Preorder Traversal 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/n-ary-tree-preorder-traversal/">589. N-ary Tree Preorder Traversal 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string"># Definition for a Node.</span></span><br><span class="line"><span class="string">class Node:</span></span><br><span class="line"><span class="string">    def __init__(self, val=None, children=None):</span></span><br><span class="line"><span class="string">        self.val = val</span></span><br><span class="line"><span class="string">        self.children = children</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">preorder</span>(<span class="params">self, root: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> root <span class="keyword">and</span> <span class="built_in">sum</span>([[root.val], *<span class="built_in">map</span>(self.preorder, root.children)], []) <span class="keyword">or</span> []</span><br></pre></td></tr></table></figure></li>
<li>递归解法，利用 and or 控制递归叶节点和普通节点<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string"># Definition for a Node.</span></span><br><span class="line"><span class="string">class Node:</span></span><br><span class="line"><span class="string">    def __init__(self, val=None, children):</span></span><br><span class="line"><span class="string">        self.val = val</span></span><br><span class="line"><span class="string">        self.children = children</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">preorder</span>(<span class="params">self, root: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        s = <span class="built_in">bool</span>(root) * [root]</span><br><span class="line">        r = []</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">while</span> s:</span><br><span class="line">            root = s.pop()</span><br><span class="line">            r.append(root.val)</span><br><span class="line">            s += root.children[::-<span class="number">1</span>]</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>迭代解法</li>
<li>root 为 <code>[]</code> 时 bool 值为 <code>False</code> 同 <code>0</code>，乘法结果为 <code>[]</code>，即可跳过 <code>while</code></li>
<li>root 非空时 dfs 栈式迭代</li>
<li>逆转 <code>children</code> 是由于栈的 <code>FILO(先入后出)</code> 特性</li>
</ul>
<h2 id="599-Minimum-Index-Sum-of-Two-Lists-2行"><a href="#599-Minimum-Index-Sum-of-Two-Lists-2行" class="headerlink" title="599. Minimum Index Sum of Two Lists 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/minimum-index-sum-of-two-lists/">599. Minimum Index Sum of Two Lists 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findRestaurant</span>(<span class="params">self, list1: <span class="type">List</span>[<span class="built_in">str</span>], list2: <span class="type">List</span>[<span class="built_in">str</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">str</span>]:</span><br><span class="line">        d = &#123;x: list1.index(x) + list2.index(x) <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">set</span>(list1) &amp; <span class="built_in">set</span>(list2)&#125;</span><br><span class="line">        <span class="keyword">return</span> [x <span class="keyword">for</span> x <span class="keyword">in</span> d <span class="keyword">if</span> d[x] == <span class="built_in">min</span>(d.values())]</span><br></pre></td></tr></table></figure>
<ul>
<li>使用字典记录｛共同喜欢的商店：索引和｝，返回索引和并列最小的商店名<h2 id="652-Find-Duplicate-Subtrees-8行"><a href="#652-Find-Duplicate-Subtrees-8行" class="headerlink" title="652. Find Duplicate Subtrees 8行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/find-duplicate-subtrees/">652. Find Duplicate Subtrees 8行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findDuplicateSubtrees</span>(<span class="params">self, root</span>):</span><br><span class="line">        d = collections.defaultdict(<span class="built_in">list</span>)</span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">dfs</span>(<span class="params">root</span>):</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> root: <span class="keyword">return</span> <span class="string">&#x27;&#x27;</span></span><br><span class="line">            s = <span class="string">&#x27; &#x27;</span>.join((<span class="built_in">str</span>(root.val), dfs(root.left), dfs(root.right)))</span><br><span class="line">            d[s].append(root)</span><br><span class="line">            <span class="keyword">return</span> s</span><br><span class="line">        dfs(root)</span><br><span class="line">        <span class="keyword">return</span> [l[<span class="number">0</span>] <span class="keyword">for</span> l <span class="keyword">in</span> d.values() <span class="keyword">if</span> <span class="built_in">len</span>(l) &gt; <span class="number">1</span>]</span><br></pre></td></tr></table></figure></li>
<li>使用字典 d 记录<code>｛子树结构：[root1，root2，……]｝</code><h2 id="658-Find-K-Closest-Elements-2行"><a href="#658-Find-K-Closest-Elements-2行" class="headerlink" title="658. Find K Closest Elements 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/find-k-closest-elements/">658. Find K Closest Elements 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findClosestElements</span>(<span class="params">self, arr: <span class="type">List</span>[<span class="built_in">int</span>], k: <span class="built_in">int</span>, x: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sorted</span>(heapq.nsmallest(k, arr, key=<span class="keyword">lambda</span> n:(<span class="built_in">abs</span>(n - x), n)))</span><br></pre></td></tr></table></figure></li>
<li><code>nsmallest</code> 函数可以输出最小的N个数字，可参考<a target="_blank" rel="noopener" href="https://www.baidu.com/link?url=6R6W8O3Ro6GQpHhQiuPUf5xvcYGSc9_8mB5lClF9-zM7kNYA1vszVmT63if0YPWPIT14W1_a_GnCPyunEW2q_yJmIYdjCqNiIlW-cp51tty&amp;wd=&amp;eqid=d729203a0001d4d8000000065d2ead3f">这里</a><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findClosestElements</span>(<span class="params">self, arr: <span class="type">List</span>[<span class="built_in">int</span>], k: <span class="built_in">int</span>, x: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">len</span>(arr) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> l &lt; h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> arr[m] &gt;= x:</span><br><span class="line">                h = m</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sorted</span>(<span class="built_in">sorted</span>(arr[<span class="built_in">max</span>(<span class="number">0</span>, l-k) : l+k], key=<span class="keyword">lambda</span> y: <span class="built_in">abs</span>(y - x))[:k])</span><br></pre></td></tr></table></figure></li>
<li>二分查找法<h2 id="700-Search-in-a-Binary-Search-Tree-1行"><a href="#700-Search-in-a-Binary-Search-Tree-1行" class="headerlink" title="700. Search in a Binary Search Tree 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/search-in-a-binary-search-tree/">700. Search in a Binary Search Tree 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">searchBST</span>(<span class="params">self, root: TreeNode, val: <span class="built_in">int</span></span>) -&gt; TreeNode:</span><br><span class="line">        <span class="keyword">return</span> root <span class="keyword">and</span> (root.val == val <span class="keyword">and</span> root <span class="keyword">or</span> self.searchBST((root.left, root.right)[root.val &lt; val], val))</span><br></pre></td></tr></table></figure></li>
<li>递归<h2 id="703-Kth-Largest-Element-in-a-Stream-3行"><a href="#703-Kth-Largest-Element-in-a-Stream-3行" class="headerlink" title="703. Kth Largest Element in a Stream 3行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/kth-largest-element-in-a-stream/">703. Kth Largest Element in a Stream 3行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">KthLargest</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, k: <span class="built_in">int</span>, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>):</span><br><span class="line">        self.k, self.n = k, <span class="built_in">sorted</span>(nums)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">add</span>(<span class="params">self, val: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        self.n.insert(bisect.bisect_left(self.n, val, <span class="number">0</span>, <span class="built_in">len</span>(self.n)), val)</span><br><span class="line">        <span class="keyword">return</span> self.n[-self.k]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your KthLargest object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = KthLargest(k, nums)</span></span><br><span class="line"><span class="comment"># param_1 = obj.add(val)</span></span><br></pre></td></tr></table></figure></li>
<li>首先对数组排序</li>
<li>每次插入新值时使用二分查找搜索插入位置，保持插入后数组的升序性质，那么就可以直接取第 k 大的值</li>
<li>时间复杂度 $O(T\log N)$, 其中 T 代表插入次数</li>
<li>其实可以在每次插入之后丢弃小于第 k 大数据之后的所有数字，这样时间复杂度可以降为 $O(T\log k)$</li>
<li>进阶可使用堆：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">KthLargest</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, k: <span class="built_in">int</span>, nums</span>):</span><br><span class="line">        self.k, self.nums = k, heapq.nlargest(k, nums + [<span class="built_in">float</span>(<span class="string">&#x27;-inf&#x27;</span>)])</span><br><span class="line">        heapq.heapify(self.nums)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">add</span>(<span class="params">self, val: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        heapq.heappushpop(self.nums,val)</span><br><span class="line">        <span class="keyword">return</span> self.nums[<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your KthLargest object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = KthLargest(k, nums)</span></span><br><span class="line"><span class="comment"># param_1 = obj.add(val)</span></span><br></pre></td></tr></table></figure></li>
<li>题目中提到 $len(nums) \ge k-1$，因此我们加入一个无穷小使得 $len(nums) \ge k$，以便构造一个 $k$ 尺寸的小根堆</li>
<li>堆中的数据意味着从第 $k$ 大的数字到最大的数字</li>
<li>维护堆的时间复杂度为 $O(T\log k)$</li>
</ul>
<h2 id="724-Find-Pivot-Index-4行"><a href="#724-Find-Pivot-Index-4行" class="headerlink" title="724. Find Pivot Index 4行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/find-pivot-index/">724. Find Pivot Index 4行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pivotIndex</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        l, r, diff = <span class="number">0</span>, <span class="number">0</span>, [<span class="number">0</span>] * <span class="built_in">len</span>(nums)</span><br><span class="line">        <span class="keyword">for</span> i, j <span class="keyword">in</span> <span class="built_in">zip</span>(<span class="built_in">range</span>(<span class="built_in">len</span>(nums)), <span class="built_in">range</span>(<span class="built_in">len</span>(nums) - <span class="number">1</span>, -<span class="number">1</span>, -<span class="number">1</span>)):</span><br><span class="line">            diff[i] += l; l += nums[i]; diff[j] -= r; r += nums[j]</span><br><span class="line">        <span class="keyword">return</span> diff.index(<span class="number">0</span>) <span class="keyword">if</span> <span class="number">0</span> <span class="keyword">in</span> diff <span class="keyword">else</span> -<span class="number">1</span></span><br></pre></td></tr></table></figure>
<ul>
<li>本题利用双指针，利用 i，j 双向遍历数组。</li>
<li>l 记录当前索引左边所有数字之和，r 记录右边的和</li>
<li>diff 记录当前索引左边所有数字之和 - 右边所有数字之和，中心索引左右和相等，diff[中心索引] 为 0<h2 id="733-Flood-Fill-6行"><a href="#733-Flood-Fill-6行" class="headerlink" title="733. Flood Fill 6行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/flood-fill/">733. Flood Fill 6行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">floodFill</span>(<span class="params">self, image: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]], sr: <span class="built_in">int</span>, sc: <span class="built_in">int</span>, newColor: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        <span class="keyword">if</span> image[sr][sc] != newColor: <span class="comment"># 根剪枝</span></span><br><span class="line">            old, image[sr][sc], m, n = image[sr][sc], newColor, <span class="built_in">len</span>(image), <span class="built_in">len</span>(image[<span class="number">0</span>])</span><br><span class="line">            <span class="keyword">for</span> i, j <span class="keyword">in</span> <span class="built_in">zip</span>((sr, sr+<span class="number">1</span>, sr, sr-<span class="number">1</span>), (sc+<span class="number">1</span>, sc, sc-<span class="number">1</span>, sc)): <span class="comment"># 放入周围节点</span></span><br><span class="line">                <span class="keyword">if</span> <span class="number">0</span> &lt;= i &lt; m <span class="keyword">and</span> <span class="number">0</span> &lt;= j &lt; n <span class="keyword">and</span> image[i][j] == old: <span class="comment"># 邻剪枝</span></span><br><span class="line">                    self.floodFill(image, i, j, newColor)</span><br><span class="line">        <span class="keyword">return</span> image</span><br></pre></td></tr></table></figure>
<h2 id="739-Daily-Temperatures-5行"><a href="#739-Daily-Temperatures-5行" class="headerlink" title="739. Daily Temperatures 5行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/daily-temperatures/">739. Daily Temperatures 5行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">dailyTemperatures</span>(<span class="params">self, T</span>):</span><br><span class="line">        stack, r = [], [<span class="number">0</span>] * <span class="built_in">len</span>(T)</span><br><span class="line">        <span class="keyword">for</span> i, t <span class="keyword">in</span> <span class="built_in">enumerate</span>(T):</span><br><span class="line">            <span class="keyword">while</span> stack <span class="keyword">and</span> T[stack[-<span class="number">1</span>]] &lt; t: r[stack.pop()] = i - stack[-<span class="number">1</span>]</span><br><span class="line">            stack.append(i)</span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>入栈条件：当前元素比栈顶元素小，出栈条件：遇到比自己大的温度，出栈时索引距离即天数差<h2 id="744-Find-Smallest-Letter-Greater-Than-Target"><a href="#744-Find-Smallest-Letter-Greater-Than-Target" class="headerlink" title="744. Find Smallest Letter Greater Than Target"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/find-smallest-letter-greater-than-target/">744. Find Smallest Letter Greater Than Target</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">nextGreatestLetter</span>(<span class="params">self, letters: <span class="type">List</span>[<span class="built_in">str</span>], target: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        l = [x &gt; target <span class="keyword">for</span> x <span class="keyword">in</span> letters]</span><br><span class="line">        <span class="keyword">return</span> letters[l.index(<span class="built_in">max</span>(l))]</span><br></pre></td></tr></table></figure></li>
<li>返回列表中大于 target 的第一个字符或第一个字符（如果没有比 target 大的字符）<h2 id="747-Largest-Number-At-Least-Twice-of-Others-2行"><a href="#747-Largest-Number-At-Least-Twice-of-Others-2行" class="headerlink" title="747. Largest Number At Least Twice of Others 2行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/largest-number-at-least-twice-of-others/">747. Largest Number At Least Twice of Others 2行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">dominantIndex</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        a, b = ([<span class="number">0</span>] + <span class="built_in">sorted</span>(nums))[-<span class="number">2</span>:]</span><br><span class="line">        <span class="keyword">return</span> (-<span class="number">1</span>, nums.index(b))[b &gt;= <span class="number">2</span> * a]</span><br></pre></td></tr></table></figure></li>
<li>前面加个[0]防止数组长度不够</li>
<li>只要数组中第一大的数字不小于第二大数字的两倍即满足条件<h2 id="752-Open-the-Lock-11行"><a href="#752-Open-the-Lock-11行" class="headerlink" title="752. Open the Lock 11行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/open-the-lock/">752. Open the Lock 11行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">openLock</span>(<span class="params">self, deadends: <span class="type">List</span>[<span class="built_in">str</span>], target: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="string">&#x27;0000&#x27;</span> <span class="keyword">in</span> deadends: <span class="keyword">return</span> -<span class="number">1</span></span><br><span class="line">        deadends, q = <span class="built_in">set</span>(deadends), [(<span class="string">&#x27;0000&#x27;</span>, <span class="number">0</span>)]</span><br><span class="line">        <span class="keyword">while</span> q:</span><br><span class="line">            node, step = q.pop(<span class="number">0</span>)</span><br><span class="line">            <span class="keyword">for</span> i, add <span class="keyword">in</span> <span class="built_in">zip</span>([*<span class="built_in">range</span>(<span class="number">4</span>)] * <span class="number">2</span>, [<span class="number">1</span>] * <span class="number">4</span> + [-<span class="number">1</span>] * <span class="number">4</span>):</span><br><span class="line">                cur = node[:i] + <span class="built_in">str</span>((<span class="built_in">int</span>(node[i]) + add) % <span class="number">10</span>) + node[i+<span class="number">1</span>:]</span><br><span class="line">                <span class="keyword">if</span> cur == target: <span class="keyword">return</span> step + <span class="number">1</span></span><br><span class="line">                <span class="keyword">if</span> <span class="keyword">not</span> cur <span class="keyword">in</span> deadends:</span><br><span class="line">                    q.append((cur, step + <span class="number">1</span>))</span><br><span class="line">                    deadends.add(cur)</span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span></span><br></pre></td></tr></table></figure></li>
<li>为什么这题要用 BFS(广度优先搜索) ？根据题意，我们需要找到最少的解锁步数，这实际上可以认为是在图上搜索最短路径。BFS 总是优先搜索距离根节点近的节点，因此它搜索到的路径就是最短路径</li>
<li>以当前锁上的数字为根，所有能达到的数字为一阶邻域（子节点）进行搜索<h2 id="771-Jewels-and-Stones-1行"><a href="#771-Jewels-and-Stones-1行" class="headerlink" title="771. Jewels and Stones 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/jewels-and-stones/">771. Jewels and Stones 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">numJewelsInStones</span>(<span class="params">self, J: <span class="built_in">str</span>, S: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sum</span>(S.count(i) <span class="keyword">for</span> i <span class="keyword">in</span> J)</span><br></pre></td></tr></table></figure></li>
<li>时间复杂度$O(N^2)$，另附$O(N)$解法（set内部实现为dict，in操作时间复杂度为$O(N)$）  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">numJewelsInStones</span>(<span class="params">self, J: <span class="built_in">str</span>, S: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">	j = <span class="built_in">set</span>(J)</span><br><span class="line">	<span class="keyword">return</span> <span class="built_in">sum</span>(s <span class="keyword">in</span> j <span class="keyword">for</span> s <span class="keyword">in</span> S)</span><br></pre></td></tr></table></figure>
<h2 id="867-Transpose-Matrix-1行"><a href="#867-Transpose-Matrix-1行" class="headerlink" title="867. Transpose Matrix 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/transpose-matrix/">867. Transpose Matrix 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">transpose</span>(<span class="params">self, A: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]</span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        <span class="keyword">return</span> [*<span class="built_in">zip</span>(*A)]</span><br></pre></td></tr></table></figure>
<h2 id="938-Range-Sum-of-BST-1行"><a href="#938-Range-Sum-of-BST-1行" class="headerlink" title="938. Range Sum of BST 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/range-sum-of-bst/">938. Range Sum of BST 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">rangeSumBST</span>(<span class="params">self, root: TreeNode, L: <span class="built_in">int</span>, R: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> root <span class="keyword">and</span> root.val * (L &lt;= root.val &lt;= R) + self.rangeSumBST(root.left, L, R) + self.rangeSumBST(root.right, L, R) <span class="keyword">or</span> <span class="number">0</span></span><br></pre></td></tr></table></figure>
<h2 id="953-Verifying-an-Alien-Dictionary-1行"><a href="#953-Verifying-an-Alien-Dictionary-1行" class="headerlink" title="953. Verifying an Alien Dictionary 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/verifying-an-alien-dictionary/">953. Verifying an Alien Dictionary 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isAlienSorted</span>(<span class="params">self, words, order</span>):</span><br><span class="line">        <span class="keyword">return</span> words == <span class="built_in">sorted</span>(words, key=<span class="keyword">lambda</span> w: [order.index(x) <span class="keyword">for</span> x <span class="keyword">in</span> w])</span><br></pre></td></tr></table></figure></li>
<li>充分利用 python 序列比较的特点，sorted 的参数 key 可传入一个函数，sorted 函数会将每个元素作为输入，输入到 key 函数并获得返回值，整个序列将按此值的大小来排序。此处 key 函数为<code>lambda w: [order.index(x) for x in w]</code>，其为words中每个单词 word 返回一个 list，list 中每个元素为单词中字母 x 在 order 中的索引。比如当 order 为 ‘abcde……’ 时，单词 ‘cab’ 将返回 [3, 2, 1]。关于俩个 list 的大小比较，服从 python 序列比较的特性，请参考官方文档教程 5.8 节内容。</li>
<li><p>另外一个通用的方法是简单的数学计算，给每个单词赋予一个数字然后排序对比和原来的数组是否一致即可，每个字母的价值按字母表顺序，第几个就代表几，每进一位需要<code>*10^-2</code>避免冲突，比如字母表是<code>abcde……</code>，单词 cab 的价值就是 <code>3 * 1 + 1 * 0.01 + 2 * 0.0001</code>，价值越小的单词位置应该越靠前</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isAlienSorted</span>(<span class="params">self, words: <span class="type">List</span>[<span class="built_in">str</span>], order: <span class="built_in">str</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">	d = &#123;c: i + <span class="number">1</span> <span class="keyword">for</span> i, c <span class="keyword">in</span> <span class="built_in">enumerate</span>(order)&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="built_in">sorted</span>(words, key=<span class="keyword">lambda</span> x: <span class="built_in">sum</span>(d[c] * <span class="number">10</span>**(-<span class="number">2</span> * i) <span class="keyword">for</span> i, c <span class="keyword">in</span> <span class="built_in">enumerate</span>(x))) == words</span><br></pre></td></tr></table></figure>
<h2 id="973-K-Closest-Points-to-Origin-1行"><a href="#973-K-Closest-Points-to-Origin-1行" class="headerlink" title="973. K Closest Points to Origin 1行"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/k-closest-points-to-origin/">973. K Closest Points to Origin 1行</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">kClosest</span>(<span class="params">self, points: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]], K: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sorted</span>(points, key=<span class="keyword">lambda</span> x: x[<span class="number">0</span>]**<span class="number">2</span> + x[<span class="number">1</span>]**<span class="number">2</span>)[:K]</span><br></pre></td></tr></table></figure>
<h2 id="1290-Convert-Binary-Number-in-a-Linked-List-to-Integer"><a href="#1290-Convert-Binary-Number-in-a-Linked-List-to-Integer" class="headerlink" title="1290. Convert Binary Number in a Linked List to Integer"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/">1290. Convert Binary Number in a Linked List to Integer</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">getDecimalValue</span>(<span class="params">self, head: ListNode</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        r = <span class="number">0</span></span><br><span class="line">        <span class="keyword">while</span> head: r, head = r &lt;&lt; <span class="number">1</span> | head.val, head.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>$O(N)$, 位运算<h1 id="专题探索"><a href="#专题探索" class="headerlink" title="专题探索"></a>专题探索</h1><img src="思维导图.jpg" alt="思维导图"></li>
</ul>
<p>以上是一张互联网公司面试中经常考察的问题类型总结的思维导图，此栏目将根据 LeetCode 中文版探索板块给出的路线制作题解，各专栏将尽力覆盖各大知识要点并总结知识点和套路。相比于<a href="#题库解析">题库解析</a>部分追求代码的绝对精简，本专题追求以<strong>高可读性</strong>呈现各大专题的<strong>常规思路</strong>，为后续的题库解析部分做铺垫。俩部分题目可能重复，但专题部分会有更详细的解析，且可能运用不同解法。</p>
<h2 id="数据结构，说难也不难"><a href="#数据结构，说难也不难" class="headerlink" title="数据结构，说难也不难"></a>数据结构，说难也不难</h2><h3 id="🌠-队列-amp-栈"><a href="#🌠-队列-amp-栈" class="headerlink" title="🌠 队列 &amp; 栈"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/queue-stack/">🌠 队列 &amp; 栈</a></h3><ul>
<li>【知识卡片】Python 有内置的高效<strong>模块</strong>实现队列/栈/优先队列：<a target="_blank" rel="noopener" href="https://www.baidu.com/link?url=ucsY59H7zFlkJcIFNblaRqxfOmas8kRjDDro5uV3D8R2QVWWRNXWPKm2yQNAZBmOd6YGClvCsS8sZJsTTmMqGq&amp;wd=&amp;eqid=cbe60f050006128b000000065cd99a2e">queue模块</a></li>
<li>栈一般使用 list 直接实现</li>
<li>Python 的 collections 模块提供的<a target="_blank" rel="noopener" href="https://www.baidu.com/link?url=-qZCpylhJB1LQ_DMC_6eJil4g9xLaHI8IbSsHpfxG1ZEPKH_AFN8sptkOXkKqjDr0E5atG6QSLELpTSww6Z3UKnLEf0eSppKGfssCw7fq3m&amp;wd=&amp;eqid=821793550017be6e000000065ce99df2"> 双向队列 collections.deque </a>同时具有 栈 和 队列 的性质，也是一个不错的选择</li>
</ul>
<p>☄ <strong>队列：先入先出的数据结构</strong></p>
<ul>
<li>【知识卡片】<strong>队列</strong>中的数据呈线性排列，就和“队列”这个名字一样，把它想象成排成一 队的人更容易理解。在队列中，处理总是从第一名开始往后进行，而新来的人只能排在队尾。像队列这种最先进去的数据最先被取来，即“先进先出”的结构，我们称为 First In First Out，简称 FIFO<h4 id="622-设计循环队列"><a href="#622-设计循环队列" class="headerlink" title="622. 设计循环队列"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/design-circular-queue/">622. 设计循环队列</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">MyCircularQueue</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, k: <span class="built_in">int</span></span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Initialize your data structure here. Set the size of the queue to be k.</span></span><br><span class="line"><span class="string">        :param k:</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.size = <span class="number">0</span></span><br><span class="line">        self.max_size = k</span><br><span class="line">        self.data = [<span class="number">0</span>] * k</span><br><span class="line">        self.front = self.rear = -<span class="number">1</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">enQueue</span>(<span class="params">self, value: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Insert an element into the circular queue. Return true if the operation is successful.</span></span><br><span class="line"><span class="string">        :param value:</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">if</span> self.isFull():</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> self.rear == -<span class="number">1</span>:</span><br><span class="line">            self.rear = self.front = <span class="number">0</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            self.rear = (self.rear + <span class="number">1</span>) % self.max_size</span><br><span class="line"></span><br><span class="line">        self.data[self.rear] = value</span><br><span class="line">        self.size += <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">deQueue</span>(<span class="params">self</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Delete an element from the circular queue. Return true if the operation is successful.</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">if</span> self.isEmpty():</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> self.front == self.rear:</span><br><span class="line">            self.front = self.rear = -<span class="number">1</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            self.front = (self.front + <span class="number">1</span>) % self.max_size</span><br><span class="line">        self.size -= <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">Front</span>(<span class="params">self</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Get the front item from the queue.</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> self.data[self.front] <span class="keyword">if</span> self.size != <span class="number">0</span> <span class="keyword">else</span> -<span class="number">1</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">Rear</span>(<span class="params">self</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Get the last item from the queue.</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> self.data[self.rear] <span class="keyword">if</span> self.size != <span class="number">0</span> <span class="keyword">else</span> -<span class="number">1</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isEmpty</span>(<span class="params">self</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Checks whether the circular queue is empty or not.</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> self.size == <span class="number">0</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isFull</span>(<span class="params">self</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Checks whether the circular queue is full or not.</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> self.size == self.max_size</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your MyCircularQueue object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = MyCircularQueue(k)</span></span><br><span class="line"><span class="comment"># param_1 = obj.enQueue(value)</span></span><br><span class="line"><span class="comment"># param_2 = obj.deQueue()</span></span><br><span class="line"><span class="comment"># param_3 = obj.Front()</span></span><br><span class="line"><span class="comment"># param_4 = obj.Rear()</span></span><br><span class="line"><span class="comment"># param_5 = obj.isEmpty()</span></span><br><span class="line"><span class="comment"># param_6 = obj.isFull()</span></span><br></pre></td></tr></table></figure></li>
<li>此处为体现数据结构，直接使用list，list.pop(0)耗时较多，Python 有内置的高效模块实现队列/栈/优先队列：<a target="_blank" rel="noopener" href="https://www.baidu.com/link?url=ucsY59H7zFlkJcIFNblaRqxfOmas8kRjDDro5uV3D8R2QVWWRNXWPKm2yQNAZBmOd6YGClvCsS8sZJsTTmMqGq&amp;wd=&amp;eqid=cbe60f050006128b000000065cd99a2e">queue模块</a></li>
</ul>
<p>☄ <strong>队列和广度优先搜索</strong></p>
<ul>
<li>【知识卡片】<strong>广度优先搜索 BFS</strong> 是一种对图进行搜索的算法。假设我们一开始位于某个顶点（即起点），此 时并不知道图的整体结构，而我们的目的是从起点开始顺着边搜索，直到到达指定顶点（即终 点）。在此过程中每走到一个顶点，就会判断一次它是否为终点。广度优先搜索会优先从离起点近的顶点开始搜索，这样由近及广的搜索方式也使得。根据 BFS 的特性，其常常被用于 <code>遍历</code> 和 <code>搜索最短路径</code></li>
<li>【套路】<strong>BFS</strong>一般流程：  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">BFS</span>(<span class="params">self</span>):</span><br><span class="line">	<span class="comment"># 1.使用 queue.Queue 初始化队列</span></span><br><span class="line">	<span class="comment"># 2.选择合适的根节点压入队列</span></span><br><span class="line"></span><br><span class="line">	<span class="comment"># 3.使用 wile 进入队列循环，直到搜索完毕</span></span><br><span class="line">	<span class="comment"># &#123;</span></span><br><span class="line">	<span class="comment">#   4.取出一个节点</span></span><br><span class="line">	<span class="comment">#   5.放入这个节点周围的节点</span></span><br><span class="line">	<span class="comment"># &#125;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>使用 BFS 时，需要抓住 3 个关键点：根节点是什么？根节点的一阶邻域节点是哪些？什么时候停止搜索？<h4 id="200-岛屿的个数"><a href="#200-岛屿的个数" class="headerlink" title="200. 岛屿的个数"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/number-of-islands/">200. 岛屿的个数</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> queue <span class="keyword">import</span> Queue</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">numIslands</span>(<span class="params">self, grid</span>):</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            r = <span class="number">0</span>; m = <span class="built_in">len</span>(grid); n = <span class="built_in">len</span>(grid[<span class="number">0</span>])</span><br><span class="line">            around = ((<span class="number">0</span>, <span class="number">1</span>), (<span class="number">1</span>, <span class="number">0</span>), (<span class="number">0</span>, -<span class="number">1</span>), (-<span class="number">1</span>, <span class="number">0</span>))</span><br><span class="line">        <span class="keyword">except</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">        </span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(m):</span><br><span class="line">            <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(n):</span><br><span class="line">                <span class="keyword">if</span> <span class="built_in">int</span>(grid[i][j]):</span><br><span class="line">                    r += <span class="number">1</span></span><br><span class="line">                    </span><br><span class="line">                    <span class="comment">#---------------------------BFS 开始-----------------------------</span></span><br><span class="line">                    <span class="comment"># 把根节点投入队列</span></span><br><span class="line">                    q = Queue()</span><br><span class="line">                    q.put((i, j))</span><br><span class="line"></span><br><span class="line">                    <span class="comment"># 开始循环</span></span><br><span class="line">                    <span class="keyword">while</span> <span class="keyword">not</span> q.empty():</span><br><span class="line">                        <span class="comment"># 取出还未沉没的陆地节点并沉没陆地（防止下次遍历到的时候再算一遍）</span></span><br><span class="line">                        x, y = q.get()</span><br><span class="line">                        </span><br><span class="line">                        <span class="keyword">if</span> <span class="built_in">int</span>(grid[x][y]):</span><br><span class="line">                            grid[x][y] = <span class="string">&#x27;0&#x27;</span></span><br><span class="line"></span><br><span class="line">                            <span class="comment"># 放入周围的陆地节点</span></span><br><span class="line">                            <span class="keyword">for</span> a, b <span class="keyword">in</span> around:</span><br><span class="line">                                a += x; b += y;</span><br><span class="line">                                <span class="keyword">if</span> <span class="number">0</span> &lt;= a &lt; m <span class="keyword">and</span> <span class="number">0</span> &lt;= b &lt; n <span class="keyword">and</span> <span class="built_in">int</span>(grid[a][b]):</span><br><span class="line">                                    q.put((a, b))</span><br><span class="line">                    <span class="comment">#----------------------------------------------------------------</span></span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li>BFS解法在这题很慢但是很常规</li>
<li>算法书中的 BFS 一般都是以树为例子介绍的，那么在本题中如何应用 BFS ？ 根据题意，我们可以把每一个陆地点当作树根，用 BFS 搜索四周的陆地并沉没它，那么这一整块的陆地都被沉没了，下次我们再遇到陆地点的时候就说明发现新大陆了 🙊<h4 id="752-打开转盘锁"><a href="#752-打开转盘锁" class="headerlink" title="752. 打开转盘锁"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/open-the-lock/submissions/">752. 打开转盘锁</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> queue <span class="keyword">import</span> Queue</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">openLock</span>(<span class="params">self, deadends: <span class="type">List</span>[<span class="built_in">str</span>], target: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        deadends = <span class="built_in">set</span>(deadends) <span class="comment"># in 操作在set中时间复杂度为O(1)</span></span><br><span class="line">        <span class="keyword">if</span> <span class="string">&#x27;0000&#x27;</span> <span class="keyword">in</span> deadends:</span><br><span class="line">            <span class="keyword">return</span> -<span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> target == <span class="string">&#x27;0000&#x27;</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment"># -------------------------------BFS 开始----------------------------------</span></span><br><span class="line">        <span class="comment"># 初始化根节点</span></span><br><span class="line">        q = Queue()</span><br><span class="line">        q.put((<span class="string">&#x27;0000&#x27;</span>, <span class="number">0</span>)) <span class="comment"># (当前节点值，转动步数)</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 开始循环队列</span></span><br><span class="line">        <span class="keyword">while</span> <span class="keyword">not</span> q.empty():</span><br><span class="line">            </span><br><span class="line">            <span class="comment"># 取出一个节点</span></span><br><span class="line">            node, step = q.get()</span><br><span class="line">            </span><br><span class="line">            <span class="comment"># 放入周围节点</span></span><br><span class="line">            <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">4</span>):</span><br><span class="line">                <span class="keyword">for</span> add <span class="keyword">in</span> (<span class="number">1</span>, -<span class="number">1</span>):</span><br><span class="line">                    cur = node[:i] + <span class="built_in">str</span>((<span class="built_in">int</span>(node[i]) + add) % <span class="number">10</span>) + node[i+<span class="number">1</span>:]</span><br><span class="line">                    <span class="keyword">if</span> cur == target:</span><br><span class="line">                        <span class="keyword">return</span> step + <span class="number">1</span></span><br><span class="line">                    <span class="keyword">if</span> <span class="keyword">not</span> cur <span class="keyword">in</span> deadends:</span><br><span class="line">                        q.put((cur, step + <span class="number">1</span>))</span><br><span class="line">                        deadends.add(cur) <span class="comment"># 避免重复搜索</span></span><br><span class="line">        <span class="comment"># -------------------------------------------------------------------------</span></span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span></span><br></pre></td></tr></table></figure></li>
<li>为什么这题要用 BFS(广度优先搜索) ？根据题意，我们需要找到最少的解锁步数，这实际上可以认为是在图上搜索最短路径。BFS 总是优先搜索距离根节点近的节点，因此它搜索到的路径就是最短路径</li>
<li>以当前锁上的数字为根，所有能达到的数字为一阶邻域（子节点）进行搜索<h4 id="279-完全平方数"><a href="#279-完全平方数" class="headerlink" title="279. 完全平方数"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/perfect-squares/submissions/">279. 完全平方数</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> queue <span class="keyword">import</span> Queue</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">numSquares</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        around = []</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, n + <span class="number">1</span>):</span><br><span class="line">            <span class="keyword">if</span> i**<span class="number">2</span> &lt;= n:</span><br><span class="line">                around.append(i**<span class="number">2</span>)</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        </span><br><span class="line">        r = <span class="number">0</span></span><br><span class="line">        seen = <span class="built_in">set</span>() <span class="comment"># 防止重复运算</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment"># ----------------BFS 开始----------------------</span></span><br><span class="line">        <span class="comment"># 初始化根节点</span></span><br><span class="line">        q = Queue()</span><br><span class="line">        q.put((<span class="number">0</span>, r))</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 进入队列循环</span></span><br><span class="line">        <span class="keyword">while</span> <span class="keyword">not</span> q.empty():</span><br><span class="line">            <span class="comment"># 取出一个元素</span></span><br><span class="line">            cur, step = q.get()</span><br><span class="line">            step += <span class="number">1</span></span><br><span class="line">            </span><br><span class="line">            <span class="comment"># 放入周围元素</span></span><br><span class="line">            <span class="keyword">for</span> a <span class="keyword">in</span> around:</span><br><span class="line">                a += cur</span><br><span class="line">                <span class="keyword">if</span> a == n:</span><br><span class="line">                    <span class="keyword">return</span> step</span><br><span class="line">                <span class="keyword">if</span> a &lt; n <span class="keyword">and</span> (a, step) <span class="keyword">not</span> <span class="keyword">in</span> seen:</span><br><span class="line">                    seen.add((a, step))</span><br><span class="line">                    q.put((a, step))</span><br><span class="line">        <span class="comment"># ----------------------------------------------</span></span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span></span><br></pre></td></tr></table></figure></li>
<li>将当前数字的总和视为节点，加上一个完全平方数后能达到的数字作为一阶邻域，搜索到达 n 的最短路径</li>
</ul>
<p>☄ <strong>栈：后入先出的数据结构</strong></p>
<ul>
<li>【知识卡片】<strong>栈</strong>也是一种数据呈线性排列的数据结构，不过在这种结构中，我们只能访问最新添加的数 据。栈就像是一摞书，拿到新书时我们会把它放在书堆的最上面，取书时也只能从最上面的新书开始取。Last In First Out，简称 LIFO，常常被用于数组中不同位置之间含有 <code>嵌套关系</code> 的题目</li>
<li>【套路】<strong>栈</strong>问题关键点：<ul>
<li>解决栈问题时，主要是需要确定入栈和出栈（从栈顶弹出）的条件</li>
<li>通常来说栈内储存的元素都是同一类元素，在某个层面上有共同的性质</li>
<li>嵌套关系是指出栈时得到的栈顶元素与当前判断是否入栈元素的关系，以此作为切入点套入计算题目结果所需的俩个元素是涉及栈的关键<h4 id="155-最小栈"><a href="#155-最小栈" class="headerlink" title="155. 最小栈"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/min-stack/solution/python-mei-ge-yi-xing-by-knifezhu/">155. 最小栈</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">MinStack</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        initialize your data structure here.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.data = [(<span class="literal">None</span>, <span class="built_in">float</span>(<span class="string">&#x27;inf&#x27;</span>))]</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">push</span>(<span class="params">self, x: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        self.data.append((x, <span class="built_in">min</span>(x, self.data[-<span class="number">1</span>][<span class="number">1</span>])))</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pop</span>(<span class="params">self</span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">len</span>(self.data) &gt; <span class="number">1</span>: self.data.pop()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">top</span>(<span class="params">self</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> self.data[-<span class="number">1</span>][<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">getMin</span>(<span class="params">self</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> self.data[-<span class="number">1</span>][<span class="number">1</span>]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your MinStack object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = MinStack()</span></span><br><span class="line"><span class="comment"># obj.push(x)</span></span><br><span class="line"><span class="comment"># obj.pop()</span></span><br><span class="line"><span class="comment"># param_3 = obj.top()</span></span><br><span class="line"><span class="comment"># param_4 = obj.getMin()</span></span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li>栈中每个元组记录元素值和最小值<h4 id="20-有效的括号"><a href="#20-有效的括号" class="headerlink" title="20. 有效的括号"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/valid-parentheses/">20. 有效的括号</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isValid</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        stack = []</span><br><span class="line">        d = &#123;<span class="string">&#x27;(&#x27;</span>: <span class="string">&#x27;)&#x27;</span>, <span class="string">&#x27;[&#x27;</span>: <span class="string">&#x27;]&#x27;</span>, <span class="string">&#x27;&#123;&#x27;</span>: <span class="string">&#x27;&#125;&#x27;</span>&#125;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">for</span> p <span class="keyword">in</span> s:</span><br><span class="line">            <span class="keyword">if</span> p <span class="keyword">in</span> <span class="string">&#x27;&#123;[(&#x27;</span>:</span><br><span class="line">                stack.append(p)</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">if</span> <span class="keyword">not</span> stack <span class="keyword">or</span> d[stack.pop()] != p:</span><br><span class="line">                    <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">not</span> stack</span><br></pre></td></tr></table></figure></li>
<li>此题入栈条件为：元素是左括号，出栈条件为：匹配到右括号</li>
<li>栈中的元素全部为左括号<h4 id="739-每日温度"><a href="#739-每日温度" class="headerlink" title="739. 每日温度"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/daily-temperatures/submissions/">739. 每日温度</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">dailyTemperatures</span>(<span class="params">self, T</span>):</span><br><span class="line">        stack = []</span><br><span class="line">        r = [<span class="number">0</span>] * <span class="built_in">len</span>(T)</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">for</span> i, t <span class="keyword">in</span> <span class="built_in">enumerate</span>(T):</span><br><span class="line">            <span class="keyword">while</span> stack <span class="keyword">and</span> T[stack[-<span class="number">1</span>]] &lt; t:</span><br><span class="line">                c = stack.pop()</span><br><span class="line">                r[c] = i - c</span><br><span class="line">            stack.append(i)</span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>入栈条件：当前元素比栈顶元素小，出栈条件：遇到比自己大的温度</li>
<li>栈内元素为降序排列的温度的索引</li>
<li>出栈时索引距离即天数差<h4 id="150-逆波兰表达式求值"><a href="#150-逆波兰表达式求值" class="headerlink" title="150. 逆波兰表达式求值"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/submissions/">150. 逆波兰表达式求值</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">evalRPN</span>(<span class="params">self, tokens: <span class="type">List</span>[<span class="built_in">str</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="comment"># 初始化栈，用栈储存未处理的数字</span></span><br><span class="line">        stack = []</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 遍历元素</span></span><br><span class="line">        <span class="keyword">for</span> t <span class="keyword">in</span> tokens:</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> t <span class="keyword">in</span> <span class="string">&#x27;+-*/&#x27;</span>: <span class="comment"># 规定入栈条件</span></span><br><span class="line">                stack.append(<span class="built_in">int</span>(t))</span><br><span class="line">                </span><br><span class="line">            <span class="keyword">else</span>: <span class="comment"># 出栈：从栈顶弹出元素与新的栈顶做运算</span></span><br><span class="line">                a = stack.pop()</span><br><span class="line">                stack[-<span class="number">1</span>] = <span class="built_in">int</span>(<span class="built_in">eval</span>(<span class="built_in">str</span>(stack[-<span class="number">1</span>]) + t + <span class="string">&#x27;a&#x27;</span>))</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> stack[-<span class="number">1</span>]</span><br></pre></td></tr></table></figure></li>
<li>使用栈储存所有未处理的数字</li>
<li>出栈时，我们总是将出栈元素与新的栈顶做运算，然后用结果更新新栈顶元素</li>
</ul>
<p>☄ <strong>栈和深度优先搜索</strong></p>
<ul>
<li>【知识卡片】<strong>深度优先搜索 DFS</strong> 和广度优先搜索一样，都是对图进行搜索的算法，目的也都是从起点开始搜索直到到达指定顶点（终点）。深度优先搜索会沿着一条路径不断往下搜索直到不能再继续为止，然后再折返，开始搜索下一条候补路径。正如树的遍历中所提到的，我们可以用 DFS 进行 <code>前序遍历</code>，<code>中序遍历</code> 和 <code>后序遍历</code>。在这三个遍历顺序中有一个共同的特性：除非我们到达最深的结点，否则我们永远不会回溯<h4 id="200-岛屿的个数-1"><a href="#200-岛屿的个数-1" class="headerlink" title="200. 岛屿的个数"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/number-of-islands/">200. 岛屿的个数</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">numIslands</span>(<span class="params">self, grid: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">str</span>]]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            m = <span class="built_in">len</span>(grid)</span><br><span class="line">            n = <span class="built_in">len</span>(grid[<span class="number">0</span>])</span><br><span class="line">        <span class="keyword">except</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment"># -------------------------DFS 开始------------------------</span></span><br><span class="line">        <span class="comment"># 定义dfs递归方程</span></span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">dfs</span>(<span class="params">i, j</span>):</span><br><span class="line">            <span class="keyword">if</span> <span class="number">0</span> &lt;= i &lt; m <span class="keyword">and</span> <span class="number">0</span> &lt;= j &lt; n <span class="keyword">and</span> <span class="built_in">int</span>(grid[i][j]):</span><br><span class="line">                grid[i][j] = <span class="string">&#x27;0&#x27;</span></span><br><span class="line">                <span class="keyword">for</span> a, b <span class="keyword">in</span> ((<span class="number">1</span>, <span class="number">0</span>), (<span class="number">0</span>, -<span class="number">1</span>), (-<span class="number">1</span>, <span class="number">0</span>), (<span class="number">0</span>, <span class="number">1</span>)):</span><br><span class="line">                    dfs(i + a, j + b)</span><br><span class="line">        <span class="comment"># ---------------------------------------------------------</span></span><br><span class="line">        </span><br><span class="line">        r = <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(m):</span><br><span class="line">            <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(n):</span><br><span class="line">                r += <span class="built_in">int</span>(grid[i][j])</span><br><span class="line">                dfs(i, j) <span class="comment"># 调用dfs沉没一整块陆地</span></span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>遍历所有格点，每当发现陆地就用dfs递归沉没它周围的陆地，那么我们发现陆地的次数就是岛屿数<h4 id="133-克隆图"><a href="#133-克隆图" class="headerlink" title="133. 克隆图"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/clone-graph/">133. 克隆图</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string"># Definition for a Node.</span></span><br><span class="line"><span class="string">class Node:</span></span><br><span class="line"><span class="string">    def __init__(self, val, neighbors):</span></span><br><span class="line"><span class="string">        self.val = val</span></span><br><span class="line"><span class="string">        self.neighbors = neighbors</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">cloneGraph</span>(<span class="params">self, node: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="string">&#x27;Node&#x27;</span>:</span><br><span class="line">        d = &#123;&#125;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">dfs</span>(<span class="params">old</span>):</span><br><span class="line">            <span class="keyword">if</span> old <span class="keyword">not</span> <span class="keyword">in</span> d:</span><br><span class="line">                <span class="comment"># 每遍历一个节点就创建一个它的副本到哈希表</span></span><br><span class="line">                d[old] = new = Node(old.val, <span class="literal">None</span>)</span><br><span class="line">                <span class="comment"># 当所有节点进入哈希表之时开始回溯，修改邻居</span></span><br><span class="line">                new.neighbors = [*<span class="built_in">map</span>(dfs, old.neighbors)]</span><br><span class="line">            <span class="keyword">return</span> d[old]</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> dfs(node)</span><br></pre></td></tr></table></figure></li>
<li>此题为无向连通图的搜索，用dfs遍历整个图，并为每个节点创建副本到哈希表，当回溯之时，所有节点已经在表中，修改邻居即可<h4 id="494-目标和"><a href="#494-目标和" class="headerlink" title="494. 目标和"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/target-sum/">494. 目标和</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findTargetSumWays</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], S: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">dfs</span>(<span class="params">cur, i, d = &#123;&#125;</span>):</span><br><span class="line">            <span class="keyword">if</span> i &lt; <span class="built_in">len</span>(nums) <span class="keyword">and</span> (i, cur) <span class="keyword">not</span> <span class="keyword">in</span> d: <span class="comment"># 搜索周围节点</span></span><br><span class="line">                d[(i, cur)] = dfs(cur + nums[i], i + <span class="number">1</span>) + dfs(cur - nums[i], i + <span class="number">1</span>)</span><br><span class="line">            <span class="keyword">return</span> d.get((i, cur), <span class="built_in">int</span>(cur == S))</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> dfs(<span class="number">0</span>, <span class="number">0</span>)</span><br></pre></td></tr></table></figure></li>
<li>dfs遍历所有可能结果，以当前位置 i 和当前总和 cur 为根节点，以下一位数字的加减为邻域扩散搜索</li>
<li>利用 d 构造记忆，以便剪枝（搜索过程中遇到相同位置和相同cur值时返回值应该相同）</li>
<li>dfs中 d 参数传的是引用，所以只有第一次会采用默认值 <code>&#123;&#125;</code><h4 id="94-二叉树的中序遍历"><a href="#94-二叉树的中序遍历" class="headerlink" title="94. 二叉树的中序遍历"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/binary-tree-inorder-traversal/">94. 二叉树的中序遍历</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">inorderTraversal</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        r = []</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 初始化栈</span></span><br><span class="line">        stack = []</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 进入堆栈循环</span></span><br><span class="line">        <span class="keyword">while</span> stack <span class="keyword">or</span> root:</span><br><span class="line">            <span class="keyword">if</span> root: <span class="comment"># 入栈条件</span></span><br><span class="line">                stack.append(root)</span><br><span class="line">                root = root.left</span><br><span class="line">            <span class="keyword">else</span>: <span class="comment"># 出栈条件</span></span><br><span class="line">                root = stack.pop()</span><br><span class="line">                r.append(root.val)</span><br><span class="line">                root = root.right</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>☄ <strong>小结</strong></p>
<ul>
<li>【套路】<strong>迭代形 BFS/DFS</strong>  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">BFS</span>(<span class="params">self</span>):</span><br><span class="line">	<span class="comment"># 1.BFS 使用 queue.Queue, DFS 使用 queue.LifoQueue</span></span><br><span class="line">	<span class="comment"># 2.选择合适的根节点压入队列</span></span><br><span class="line"></span><br><span class="line">	<span class="comment"># 3.使用 wile 进入循环，直到搜索完毕</span></span><br><span class="line">	<span class="comment"># &#123;</span></span><br><span class="line">	<span class="comment">#   4.取出一个节点</span></span><br><span class="line">	<span class="comment">#   5.放入这个节点周围的节点</span></span><br><span class="line">	<span class="comment"># &#125;</span></span><br></pre></td></tr></table></figure></li>
<li>【套路】<strong>递归形 DFS</strong>  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">dfs</span>(<span class="params">self, root</span>):</span><br><span class="line">	<span class="keyword">if</span> ...: <span class="comment"># 根剪枝</span></span><br><span class="line">	    root = ... <span class="comment"># 根处理</span></span><br><span class="line">	    <span class="keyword">for</span> node <span class="keyword">in</span> around: <span class="comment"># 放入周围节点</span></span><br><span class="line">		<span class="keyword">if</span> node == ...: <span class="comment"># 邻剪枝</span></span><br><span class="line">		    self.dfs(node) <span class="comment"># 递归</span></span><br><span class="line">	<span class="keyword">return</span> image <span class="comment"># 终止返回</span></span><br></pre></td></tr></table></figure>
<h4 id="232-用栈实现队列"><a href="#232-用栈实现队列" class="headerlink" title="232. 用栈实现队列"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/implement-queue-using-stacks/">232. 用栈实现队列</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">MyQueue</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Initialize your data structure here.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.stack = []</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">push</span>(<span class="params">self, x: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Push element x to the back of queue.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.stack.append(x)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pop</span>(<span class="params">self</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Removes the element from in front of queue and returns that element.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        temp = []</span><br><span class="line">        <span class="keyword">while</span> self.stack:</span><br><span class="line">            temp.append(self.stack.pop())</span><br><span class="line">        </span><br><span class="line">        r = temp.pop()</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">while</span> temp:</span><br><span class="line">            self.stack.append(temp.pop())</span><br><span class="line">            </span><br><span class="line">        <span class="keyword">return</span> r</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">peek</span>(<span class="params">self</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Get the front element.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        temp = []</span><br><span class="line">        <span class="keyword">while</span> self.stack:</span><br><span class="line">            temp.append(self.stack.pop())</span><br><span class="line">        </span><br><span class="line">        r = temp[-<span class="number">1</span>]</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">while</span> temp:</span><br><span class="line">            self.stack.append(temp.pop())</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> r</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">empty</span>(<span class="params">self</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Returns whether the queue is empty.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">not</span> self.stack</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your MyQueue object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = MyQueue()</span></span><br><span class="line"><span class="comment"># obj.push(x)</span></span><br><span class="line"><span class="comment"># param_2 = obj.pop()</span></span><br><span class="line"><span class="comment"># param_3 = obj.peek()</span></span><br><span class="line"><span class="comment"># param_4 = obj.empty()</span></span><br></pre></td></tr></table></figure></li>
<li>使用俩个栈来模拟队列，当需要取第一个元素的时候创建一个临时的栈temp，把栈里面的东西全部抽出来放进temp，完成操作后放回去<h4 id="225-用队列实现栈"><a href="#225-用队列实现栈" class="headerlink" title="225. 用队列实现栈"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/implement-stack-using-queues/submissions/">225. 用队列实现栈</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> queue <span class="keyword">import</span> Queue</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyStack</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Initialize your data structure here.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.q = Queue()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">push</span>(<span class="params">self, x: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Push element x onto stack.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.q.put(x)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pop</span>(<span class="params">self</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Removes the element on top of the stack and returns that element.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(self.q.qsize() - <span class="number">1</span>):</span><br><span class="line">            self.q.put(self.q.get())</span><br><span class="line">        <span class="keyword">return</span> self.q.get()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">top</span>(<span class="params">self</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Get the top element.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(self.q.qsize() - <span class="number">1</span>):</span><br><span class="line">            self.q.put(self.q.get())</span><br><span class="line">        r = self.q.get()</span><br><span class="line">        self.q.put(r)</span><br><span class="line">        <span class="keyword">return</span> r</span><br><span class="line">        </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">empty</span>(<span class="params">self</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Returns whether the stack is empty.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> self.q.empty()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your MyStack object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = MyStack()</span></span><br><span class="line"><span class="comment"># obj.push(x)</span></span><br><span class="line"><span class="comment"># param_2 = obj.pop()</span></span><br><span class="line"><span class="comment"># param_3 = obj.top()</span></span><br><span class="line"><span class="comment"># param_4 = obj.empty()</span></span><br></pre></td></tr></table></figure></li>
<li>弹栈顶的时候把队列遍历一遍，每次弹出之后加入队尾，除了最后一个<h4 id="394-字符串解码"><a href="#394-字符串解码" class="headerlink" title="394. 字符串解码"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/decode-string/">394. 字符串解码</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">decodeString</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        stack = [[<span class="string">&#x27;&#x27;</span>, <span class="number">1</span>, <span class="string">&#x27;&#x27;</span>]]</span><br><span class="line">        a = n = <span class="string">&#x27;&#x27;</span></span><br><span class="line">        <span class="keyword">for</span> c <span class="keyword">in</span> s:</span><br><span class="line">            <span class="keyword">if</span> c.isalpha():</span><br><span class="line">                a += c</span><br><span class="line">            <span class="keyword">elif</span> c.isdigit():</span><br><span class="line">                n += c</span><br><span class="line">            <span class="keyword">elif</span> c == <span class="string">&#x27;[&#x27;</span>:</span><br><span class="line">                stack.append([a, <span class="built_in">int</span>(n), <span class="string">&#x27;&#x27;</span>])</span><br><span class="line">                a = n = <span class="string">&#x27;&#x27;</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                p, t, b = stack.pop()</span><br><span class="line">                stack[-<span class="number">1</span>][-<span class="number">1</span>] += p + t * (b + a)</span><br><span class="line">                a = <span class="string">&#x27;&#x27;</span></span><br><span class="line">        <span class="keyword">return</span> stack.pop()[-<span class="number">1</span>] + a</span><br></pre></td></tr></table></figure></li>
<li>用 stack 记录（[]之前的字母，翻倍次数，翻倍内容）<h4 id="733-图像渲染"><a href="#733-图像渲染" class="headerlink" title="733. 图像渲染"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/flood-fill/">733. 图像渲染</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">floodFill</span>(<span class="params">self, image: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]], sr: <span class="built_in">int</span>, sc: <span class="built_in">int</span>, newColor: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        m, n = <span class="built_in">map</span>(<span class="built_in">len</span>, (image, image[<span class="number">0</span>]))</span><br><span class="line">        around = ((<span class="number">1</span>, <span class="number">0</span>), (<span class="number">0</span>, <span class="number">1</span>), (-<span class="number">1</span>, <span class="number">0</span>), (<span class="number">0</span>, -<span class="number">1</span>))</span><br><span class="line">        oldColor = image[sr][sc]</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 创建栈放入根节点</span></span><br><span class="line">        stack = [(sr, sc)]</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 进入循环放入邻居</span></span><br><span class="line">        <span class="keyword">while</span> stack:</span><br><span class="line">            r, c = stack.pop()</span><br><span class="line">            <span class="keyword">if</span> oldColor != newColor: <span class="comment"># 根剪枝</span></span><br><span class="line">                image[r][c] = newColor</span><br><span class="line"></span><br><span class="line">                <span class="keyword">for</span> x, y <span class="keyword">in</span> around:</span><br><span class="line">                    x, y = x + r, y + c</span><br><span class="line">                    <span class="keyword">if</span> <span class="number">0</span> &lt;= x &lt; m <span class="keyword">and</span> <span class="number">0</span> &lt;= y &lt; n <span class="keyword">and</span> image[x][y] == oldColor: <span class="comment"># 邻剪枝</span></span><br><span class="line">                        image[x][y] = newColor</span><br><span class="line">                        stack.append((x, y))</span><br><span class="line">        <span class="keyword">return</span> image</span><br></pre></td></tr></table></figure>
<h4 id="542-01-矩阵"><a href="#542-01-矩阵" class="headerlink" title="542. 01 矩阵"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/01-matrix/submissions/">542. 01 矩阵</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">updateMatrix</span>(<span class="params">self, matrix: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]</span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        m, n = <span class="built_in">len</span>(matrix), <span class="built_in">len</span>(matrix[<span class="number">0</span>])</span><br><span class="line">        r = [[<span class="number">0</span>] * n <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(m)]</span><br><span class="line">        around = ((<span class="number">0</span>, <span class="number">1</span>), (<span class="number">1</span>, <span class="number">0</span>), (<span class="number">0</span>, -<span class="number">1</span>), (-<span class="number">1</span>, <span class="number">0</span>))</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(m):</span><br><span class="line">            <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(n):</span><br><span class="line">                <span class="comment"># -------------------------BFS 开始--------------------------</span></span><br><span class="line">                <span class="comment"># 放入根节点</span></span><br><span class="line">                q = collections.deque([(i, j, <span class="number">0</span>)])</span><br><span class="line">                seen = &#123;(i, j)&#125;</span><br><span class="line">                </span><br><span class="line">                <span class="comment"># 循环取节点</span></span><br><span class="line">                <span class="keyword">while</span> q:</span><br><span class="line">                    a, b, t = q.popleft()</span><br><span class="line">                    <span class="keyword">if</span> <span class="keyword">not</span> matrix[a][b]:</span><br><span class="line">                        r[i][j] = t</span><br><span class="line">                        <span class="keyword">break</span></span><br><span class="line">                    </span><br><span class="line">                    <span class="comment"># 放入邻节点</span></span><br><span class="line">                    <span class="keyword">for</span> x, y <span class="keyword">in</span> around:</span><br><span class="line">                        x, y = x + a, y + b</span><br><span class="line">                        <span class="keyword">if</span> <span class="number">0</span> &lt;= x &lt; m <span class="keyword">and</span> <span class="number">0</span> &lt;= y &lt; n <span class="keyword">and</span> (x, y) <span class="keyword">not</span> <span class="keyword">in</span> seen:</span><br><span class="line">                            seen.add((x, y))</span><br><span class="line">                            q.append((x, y, t + <span class="number">1</span>))</span><br><span class="line">                <span class="comment"># ----------------------------------------------------------</span></span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>以当前位置为根，四周为邻，bfs求最短路径，t记录路径长度<h4 id="841-钥匙和房间"><a href="#841-钥匙和房间" class="headerlink" title="841. 钥匙和房间"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/keys-and-rooms/submissions/">841. 钥匙和房间</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">canVisitAllRooms</span>(<span class="params">self, rooms: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        seen = &#123;<span class="number">0</span>&#125;</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 创建队列放入根节点</span></span><br><span class="line">        q = [<span class="number">0</span>]</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 循环取节点</span></span><br><span class="line">        <span class="keyword">while</span> q:</span><br><span class="line">            cur = q.pop(<span class="number">0</span>)</span><br><span class="line">            </span><br><span class="line">            <span class="comment"># 放入周围节点</span></span><br><span class="line">            <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">set</span>(rooms[cur]):</span><br><span class="line">                <span class="keyword">if</span> i <span class="keyword">not</span> <span class="keyword">in</span> seen: <span class="comment"># 剪枝</span></span><br><span class="line">                    seen.add(i)</span><br><span class="line">                    q.append(i)</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">len</span>(seen) == <span class="built_in">len</span>(rooms)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="🌠-数组和字符串"><a href="#🌠-数组和字符串" class="headerlink" title="🌠 数组和字符串"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/array-and-string/">🌠 数组和字符串</a></h3><p>☄ <strong>数组简介</strong></p>
<ul>
<li>【套路】<strong>数组</strong>问题必备锦囊：<ul>
<li>有些题目在做题之前对数组排序往往可以简化解法</li>
<li>数组与字符串大体相似但在细节上会有不同，有时候相互转化可以简化问题<h4 id="724-寻找数组的中心索引"><a href="#724-寻找数组的中心索引" class="headerlink" title="724. 寻找数组的中心索引"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-pivot-index/submissions/">724. 寻找数组的中心索引</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">pivotIndex</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        l, r, diff = <span class="number">0</span>, <span class="number">0</span>, [<span class="number">0</span>] * <span class="built_in">len</span>(nums)</span><br><span class="line">        <span class="keyword">for</span> i, j <span class="keyword">in</span> <span class="built_in">zip</span>(<span class="built_in">range</span>(<span class="built_in">len</span>(nums)), <span class="built_in">range</span>(<span class="built_in">len</span>(nums) - <span class="number">1</span>, -<span class="number">1</span>, -<span class="number">1</span>)):</span><br><span class="line">            diff[i] += l</span><br><span class="line">	    l += nums[i]</span><br><span class="line">	    diff[j] -= r</span><br><span class="line">	    r += nums[j]</span><br><span class="line">        <span class="keyword">return</span> diff.index(<span class="number">0</span>) <span class="keyword">if</span> <span class="number">0</span> <span class="keyword">in</span> diff <span class="keyword">else</span> -<span class="number">1</span></span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li>本题利用双指针，利用 i，j 双向遍历数组。</li>
<li>l 记录当前索引左边所有数字之和，r 记录右边的和</li>
<li>diff 记录当前索引左边所有数字之和 - 右边所有数字之和，中心索引左右和相等，diff[中心索引] 为 0<h4 id="747-至少是其他数字两倍的最大数"><a href="#747-至少是其他数字两倍的最大数" class="headerlink" title="747. 至少是其他数字两倍的最大数"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/largest-number-at-least-twice-of-others/submissions/">747. 至少是其他数字两倍的最大数</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">dominantIndex</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        m = <span class="built_in">max</span>(nums)</span><br><span class="line">        r = nums.index(m)</span><br><span class="line">        nums.remove(m)</span><br><span class="line">        <span class="keyword">return</span> (-<span class="number">1</span>, r)[<span class="keyword">not</span> nums <span class="keyword">or</span> m &gt;= <span class="number">2</span> * <span class="built_in">max</span>(nums)]</span><br></pre></td></tr></table></figure></li>
<li>只要数组中第一大的数字不小于第二大数字的两倍即满足条件</li>
<li>2行排序解法 → <a href="#747-Largest-Number-At-Least-Twice-of-Others-2行">戳这里</a><h4 id="66-加一"><a href="#66-加一" class="headerlink" title="66. 加一"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/plus-one/submissions/">66. 加一</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">plusOne</span>(<span class="params">self, digits: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="built_in">int</span>, <span class="built_in">str</span>(<span class="built_in">int</span>(<span class="string">&#x27;&#x27;</span>.join(<span class="built_in">map</span>(<span class="built_in">str</span>, digits))) + <span class="number">1</span>)))</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>☄ <strong>二维数组简介</strong></p>
<h4 id="498-对角线遍历"><a href="#498-对角线遍历" class="headerlink" title="498. 对角线遍历"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/diagonal-traverse/submissions/">498. 对角线遍历</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findDiagonalOrder</span>(<span class="params">self, matrix: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        m, n, r = <span class="built_in">len</span>(matrix), <span class="built_in">len</span>(matrix) <span class="keyword">and</span> <span class="built_in">len</span>(matrix[<span class="number">0</span>]), []</span><br><span class="line">        <span class="keyword">for</span> l <span class="keyword">in</span> <span class="built_in">range</span>(m + n - <span class="number">1</span>):</span><br><span class="line">            temp = [matrix[i][l - i] <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">max</span>(<span class="number">0</span>, l+<span class="number">1</span> - n), <span class="built_in">min</span>(l+<span class="number">1</span>, m))]</span><br><span class="line">            r += temp <span class="keyword">if</span> l % <span class="number">2</span> <span class="keyword">else</span> temp[::-<span class="number">1</span>]</span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure>
<ul>
<li>0 and 0 答案是 0，此处避免 matrix 为 [] 时导致报错</li>
<li>按照从右上角到左下角的顺序遍历 matrix 的所有对角线并放入列表 temp</li>
<li>如果 对角线元素个数 是偶数则应该把 temp 反转</li>
<li>把 temp 加入结果 r<h4 id="54-螺旋矩阵"><a href="#54-螺旋矩阵" class="headerlink" title="54. 螺旋矩阵"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/spiral-matrix/submissions/">54. 螺旋矩阵</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">spiralOrder</span>(<span class="params">self, matrix: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> matrix <span class="keyword">and</span> [*matrix.pop(<span class="number">0</span>)] + self.spiralOrder([*<span class="built_in">zip</span>(*matrix)][::-<span class="number">1</span>])</span><br></pre></td></tr></table></figure></li>
<li>流程图：  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">|<span class="number">1</span> <span class="number">2</span> <span class="number">3</span>|      |<span class="number">6</span> <span class="number">9</span>|      |<span class="number">8</span> <span class="number">7</span>|      |<span class="number">4</span>|  =&gt;  |<span class="number">5</span>|  =&gt;  | |</span><br><span class="line">|<span class="number">4</span> <span class="number">5</span> <span class="number">6</span>|  =&gt;  |<span class="number">5</span> <span class="number">8</span>|  =&gt;  |<span class="number">5</span> <span class="number">4</span>|  =&gt;  |<span class="number">5</span>|</span><br><span class="line">|<span class="number">7</span> <span class="number">8</span> <span class="number">9</span>|      |<span class="number">4</span> <span class="number">7</span>|</span><br></pre></td></tr></table></figure></li>
<li>为什么是<code>[*matrix.pop(0)]</code>而不是<code>matrix.pop(0)</code>？因为对于后面的递归，传进来的列表中元素是tuple<h4 id="118-杨辉三角"><a href="#118-杨辉三角" class="headerlink" title="118. 杨辉三角"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/pascals-triangle/submissions/">118. 杨辉三角</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">generate</span>(<span class="params">self, numRows: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        r = [[<span class="number">1</span>]]</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, numRows):</span><br><span class="line">            r.append([<span class="number">1</span>] + [<span class="built_in">sum</span>(r[-<span class="number">1</span>][j:j+<span class="number">2</span>]) <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(i)])</span><br><span class="line">        <span class="keyword">return</span> numRows <span class="keyword">and</span> r <span class="keyword">or</span> []</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>☄ <strong>字符串简介</strong></p>
<h4 id="67-二进制求和"><a href="#67-二进制求和" class="headerlink" title="67. 二进制求和"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/add-binary/submissions/">67. 二进制求和</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">addBinary</span>(<span class="params">self, a: <span class="built_in">str</span>, b: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        r, p = <span class="string">&#x27;&#x27;</span>, <span class="number">0</span></span><br><span class="line">        d = <span class="built_in">len</span>(b) - <span class="built_in">len</span>(a)</span><br><span class="line">        a = <span class="string">&#x27;0&#x27;</span> * d + a</span><br><span class="line">        b = <span class="string">&#x27;0&#x27;</span> * -d + b</span><br><span class="line">        <span class="keyword">for</span> i, j <span class="keyword">in</span> <span class="built_in">zip</span>(a[::-<span class="number">1</span>], b[::-<span class="number">1</span>]):</span><br><span class="line">            s = <span class="built_in">int</span>(i) + <span class="built_in">int</span>(j) + p</span><br><span class="line">            r = <span class="built_in">str</span>(s % <span class="number">2</span>) + r</span><br><span class="line">            p = s // <span class="number">2</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;1&#x27;</span> + r <span class="keyword">if</span> p <span class="keyword">else</span> r</span><br></pre></td></tr></table></figure>
<ul>
<li>此处利用了 python 的字符串乘法<h4 id="28-实现strStr"><a href="#28-实现strStr" class="headerlink" title="28. 实现strStr()"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/implement-strstr/">28. 实现strStr()</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">strStr</span>(<span class="params">self, haystack: <span class="built_in">str</span>, needle: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">		<span class="keyword">return</span> haystack.find(needle)</span><br></pre></td></tr></table></figure></li>
<li><p>不用内置函数也可以</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">	<span class="keyword">def</span> <span class="title function_">strStr</span>(<span class="params">self, haystack: <span class="string">&#x27;str&#x27;</span>, needle: <span class="string">&#x27;str&#x27;</span></span>) -&gt; <span class="string">&#x27;int&#x27;</span>:</span><br><span class="line">	    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">0</span>, <span class="built_in">len</span>(haystack) - <span class="built_in">len</span>(needle) + <span class="number">1</span>):</span><br><span class="line">	        <span class="keyword">if</span> haystack[i:i+<span class="built_in">len</span>(needle)] == needle:</span><br><span class="line">	            <span class="keyword">return</span> i</span><br><span class="line">    	<span class="keyword">return</span> -<span class="number">1</span></span><br></pre></td></tr></table></figure>
<h4 id="14-最长公共前缀"><a href="#14-最长公共前缀" class="headerlink" title="14. 最长公共前缀"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/longest-common-prefix/">14. 最长公共前缀</a></h4></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">longestCommonPrefix</span>(<span class="params">self, strs: <span class="type">List</span>[<span class="built_in">str</span>]</span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        r = [<span class="built_in">len</span>(<span class="built_in">set</span>(c)) == <span class="number">1</span> <span class="keyword">for</span> c <span class="keyword">in</span> <span class="built_in">zip</span>(*strs)] + [<span class="number">0</span>]</span><br><span class="line">        <span class="keyword">return</span> strs[<span class="number">0</span>][:r.index(<span class="number">0</span>)] <span class="keyword">if</span> strs <span class="keyword">else</span> <span class="string">&#x27;&#x27;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>利用好zip和set</li>
<li>os 模块有提供一样的函数  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">longestCommonPrefix</span>(<span class="params">self, strs: <span class="type">List</span>[<span class="built_in">str</span>]</span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">	<span class="keyword">return</span> os.path.commonprefix(strs)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>☄ <strong>双指针技巧</strong></p>
<ul>
<li>【知识卡片】<strong>双指针</strong> 通常，我们只使用从第一个元素开始并在最后一个元素结束的一个指针来进行迭代。 但是，有时候，我们可能需要同时使用两个指针来进行迭代。<ul>
<li>两个指针从 <code>不同位置</code> 出发：一个从始端开始，另一个从末端开始<ul>
<li>双向内缩</li>
<li>二分夹逼</li>
</ul>
</li>
<li>两个指针以 <code>不同速度</code> 移动：一个指针快一些，另一个指针慢一些<ul>
<li>快慢指针</li>
<li>滑动窗口<h4 id="344-反转字符串"><a href="#344-反转字符串" class="headerlink" title="344. 反转字符串"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/reverse-string/solution/python-1xing-shuang-zhi-zhen-by-knifezhu/">344. 反转字符串</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">reverseString</span>(<span class="params">self, s: <span class="type">List</span>[<span class="built_in">str</span>]</span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Do not return anything, modify s in-place instead.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        i, j = <span class="number">0</span>, <span class="built_in">len</span>(s) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> i &lt; j:</span><br><span class="line">            s[i], s[j] = s[j], s[i]</span><br><span class="line">            i += <span class="number">1</span></span><br><span class="line">            j -= <span class="number">1</span></span><br></pre></td></tr></table></figure>
<h4 id="561-数组拆分-I"><a href="#561-数组拆分-I" class="headerlink" title="561. 数组拆分 I"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/array-partition-i/submissions/">561. 数组拆分 I</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">arrayPairSum</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sum</span>(<span class="built_in">sorted</span>(nums)[::<span class="number">2</span>])</span><br></pre></td></tr></table></figure>
<h4 id="167-两数之和-II-输入有序数组"><a href="#167-两数之和-II-输入有序数组" class="headerlink" title="167. 两数之和 II - 输入有序数组"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/submissions/">167. 两数之和 II - 输入有序数组</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">twoSum</span>(<span class="params">self, numbers: <span class="type">List</span>[<span class="built_in">int</span>], target: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        i, j = <span class="number">0</span>, <span class="built_in">len</span>(numbers) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> numbers[i] + numbers[j] != target:</span><br><span class="line">            <span class="keyword">if</span> numbers[i] + numbers[j] &gt; target:</span><br><span class="line">                j -= <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> [i+<span class="number">1</span>, j+<span class="number">1</span>]</span><br></pre></td></tr></table></figure>
<h4 id="27-移除元素"><a href="#27-移除元素" class="headerlink" title="27. 移除元素"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/remove-element/submissions/">27. 移除元素</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">removeElement</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], val: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        j = <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(nums)):</span><br><span class="line">            <span class="keyword">if</span> val != nums[i]:</span><br><span class="line">                nums[j] = nums[i]</span><br><span class="line">                j += <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> j</span><br></pre></td></tr></table></figure>
<h4 id="485-最大连续1的个数"><a href="#485-最大连续1的个数" class="headerlink" title="485. 最大连续1的个数"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/max-consecutive-ones/">485. 最大连续1的个数</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findMaxConsecutiveOnes</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        r = c = <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> n <span class="keyword">in</span> nums:</span><br><span class="line">            <span class="keyword">if</span> n:</span><br><span class="line">                c += <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                r = <span class="built_in">max</span>(r, c)</span><br><span class="line">                c = <span class="number">0</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">max</span>(r, c)</span><br></pre></td></tr></table></figure>
<h4 id="209-长度最小的子数组"><a href="#209-长度最小的子数组" class="headerlink" title="209. 长度最小的子数组"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/minimum-size-subarray-sum/">209. 长度最小的子数组</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">minSubArrayLen</span>(<span class="params">self, s: <span class="built_in">int</span>, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        i, a, r = <span class="number">0</span>, <span class="number">0</span>, <span class="built_in">float</span>(<span class="string">&#x27;inf&#x27;</span>)</span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(nums)):</span><br><span class="line">            a += nums[j]</span><br><span class="line">            <span class="keyword">while</span> a &gt;= s:</span><br><span class="line">                r = <span class="built_in">min</span>(r, j - i + <span class="number">1</span>)</span><br><span class="line">                a -= nums[i]</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span> <span class="keyword">if</span> r == <span class="built_in">float</span>(<span class="string">&#x27;inf&#x27;</span>) <span class="keyword">else</span> r</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
</ul>
</li>
<li>i, j 双指针滑窗，$O(N)$时间复杂度，$O(1)$空间复杂度</li>
<li>a 代表 i 到 j 的总和</li>
</ul>
<p>☄ <strong>小结</strong></p>
<h4 id="189-旋转数组"><a href="#189-旋转数组" class="headerlink" title="189. 旋转数组"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/rotate-array/">189. 旋转数组</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">rotate</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], k: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Do not return anything, modify nums in-place instead.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(k % <span class="built_in">len</span>(nums)): nums[-<span class="number">1</span>:], nums[:<span class="number">0</span>] = [], nums[-<span class="number">1</span>:]</span><br></pre></td></tr></table></figure>
<ul>
<li>时间复杂度 = $O(k \% len(nums))$，空间复杂度 = $O(1)$<h4 id="119-杨辉三角-II"><a href="#119-杨辉三角-II" class="headerlink" title="119. 杨辉三角 II"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/pascals-triangle-ii/">119. 杨辉三角 II</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">getRow</span>(<span class="params">self, rowIndex: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        r = [<span class="number">1</span>]</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, rowIndex + <span class="number">1</span>):</span><br><span class="line">            r = [<span class="number">1</span>] + [<span class="built_in">sum</span>(r[j:j+<span class="number">2</span>]) <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(i)]</span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>跟 杨辉三角 I 没什么差别<h4 id="151-翻转字符串里的单词"><a href="#151-翻转字符串里的单词" class="headerlink" title="151. 翻转字符串里的单词"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/reverse-words-in-a-string/">151. 翻转字符串里的单词</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">reverseWords</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot; &quot;</span>.join(s.split()[::-<span class="number">1</span>])</span><br></pre></td></tr></table></figure></li>
<li>python 的 <code>split</code> 中的分隔符，默认为所有的空字符，包括空格、换行(<code>\n</code>)、制表符(<code>\t</code>)等<h4 id="557-反转字符串中的单词-III"><a href="#557-反转字符串中的单词-III" class="headerlink" title="557. 反转字符串中的单词 III"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/">557. 反转字符串中的单词 III</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">reverseWords</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27; &#x27;</span>.join(s.split()[::-<span class="number">1</span>])[::-<span class="number">1</span>]</span><br></pre></td></tr></table></figure>
<h4 id="26-删除排序数组中的重复项"><a href="#26-删除排序数组中的重复项" class="headerlink" title="26. 删除排序数组中的重复项"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/">26. 删除排序数组中的重复项</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">removeDuplicates</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        i = <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, <span class="built_in">len</span>(nums)):</span><br><span class="line">            <span class="keyword">if</span> nums[j] != nums[i]:</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">                nums[i] = nums[j]</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">len</span>(nums) <span class="keyword">and</span> i + <span class="number">1</span></span><br></pre></td></tr></table></figure></li>
<li>数组完成排序后，我们可以放置两个指针 i 和 j，其中 i 是慢指针，而 j 是快指针。只要 <code>nums[i] = nums[j]</code>，我们就增加 j 以跳过重复项。当我们遇到 <code>nums[j] != nums[i]</code>时，跳过重复项的运行已经结束，因此我们必须把它（<code>nums[j]</code>）的值复制到 <code>nums[i + 1]</code>。然后递增 i，接着我们将再次重复相同的过程，直到 j 到达数组的末尾为止<h4 id="283-移动零"><a href="#283-移动零" class="headerlink" title="283. 移动零"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/move-zeroes/submissions/">283. 移动零</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">moveZeroes</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Do not return anything, modify nums in-place instead.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        i = <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(nums)):</span><br><span class="line">            <span class="keyword">if</span> nums[j]:</span><br><span class="line">                nums[i] = nums[j]</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> i &lt; <span class="built_in">len</span>(nums):</span><br><span class="line">            nums[i] = <span class="number">0</span></span><br><span class="line">            i += <span class="number">1</span></span><br></pre></td></tr></table></figure>
<h3 id="🌠-链表"><a href="#🌠-链表" class="headerlink" title="🌠 链表"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/linked-list/">🌠 链表</a></h3></li>
<li>【知识卡片】链表是数据结构之一，其中的数据呈线性排列。在链表中，数据的添加和删除都较为方便， 就是访问比较耗费时间。实际上，相比较数组来说，并不存在链表这样一个对象，链表是由多个节点组成的，因此，我们能接触到的数据对象只有节点。我们可以根据节点来寻找周围节点，许多节点之间的关系抽象地构成了一个链表。</li>
</ul>
<p>☄ <strong>单链表</strong></p>
<h4 id="707-设计链表"><a href="#707-设计链表" class="headerlink" title="707. 设计链表"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/design-linked-list/solution/python-by-nidadianlongge/">707. 设计链表</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Node</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, v, p=<span class="literal">None</span>, n=<span class="literal">None</span></span>):</span><br><span class="line">        self.val = v</span><br><span class="line">        self.prev = p</span><br><span class="line">        self.<span class="built_in">next</span> = n</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyLinkedList</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Initialize your data structure here.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.key = Node(-<span class="number">1</span>)</span><br><span class="line">        self.key.prev = self.key.<span class="built_in">next</span> = self.key</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">get</span>(<span class="params">self, index: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Get the value of the index-th node in the linked list. If the index is invalid, return -1.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        i, node = <span class="number">0</span>, self.key.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">while</span> i &lt; index <span class="keyword">and</span> node != self.key:</span><br><span class="line">            node = node.<span class="built_in">next</span></span><br><span class="line">            i += <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> node.val <span class="keyword">if</span> index &gt;= <span class="number">0</span> <span class="keyword">else</span> -<span class="number">1</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">addAtHead</span>(<span class="params">self, val: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.key.<span class="built_in">next</span>.prev = self.key.<span class="built_in">next</span> = Node(val, p=self.key, n=self.key.<span class="built_in">next</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">addAtTail</span>(<span class="params">self, val: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Append a node of value val to the last element of the linked list.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.key.prev.<span class="built_in">next</span> = self.key.prev = Node(val, p=self.key.prev, n=self.key)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">addAtIndex</span>(<span class="params">self, index: <span class="built_in">int</span>, val: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        index = <span class="built_in">max</span>(<span class="number">0</span>, index)</span><br><span class="line">        i, node = <span class="number">0</span>, self.key.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">while</span> i &lt; index <span class="keyword">and</span> node != self.key:</span><br><span class="line">            node = node.<span class="built_in">next</span></span><br><span class="line">            i += <span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> node != self.key <span class="keyword">or</span> i == index:</span><br><span class="line">            node.prev.<span class="built_in">next</span> = node.prev = Node(val, p=node.prev, n=node)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">deleteAtIndex</span>(<span class="params">self, index: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Delete the index-th node in the linked list, if the index is valid.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">if</span> index &lt; <span class="number">0</span>: <span class="keyword">return</span></span><br><span class="line">        i, node = <span class="number">0</span>, self.key.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">while</span> i &lt; index <span class="keyword">and</span> node != self.key:</span><br><span class="line">            node = node.<span class="built_in">next</span></span><br><span class="line">            i += <span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> node != self.key:</span><br><span class="line">            node.prev.<span class="built_in">next</span> = node.<span class="built_in">next</span></span><br><span class="line">            node.<span class="built_in">next</span>.prev = node.prev</span><br><span class="line">            <span class="keyword">del</span> node</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your MyLinkedList object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = MyLinkedList()</span></span><br><span class="line"><span class="comment"># param_1 = obj.get(index)</span></span><br><span class="line"><span class="comment"># obj.addAtHead(val)</span></span><br><span class="line"><span class="comment"># obj.addAtTail(val)</span></span><br><span class="line"><span class="comment"># obj.addAtIndex(index,val)</span></span><br><span class="line"><span class="comment"># obj.deleteAtIndex(index)</span></span><br></pre></td></tr></table></figure>
<ul>
<li>本题构建了一个双向的环形链表，记录 <code>key</code> 节点，<code>key.next</code> 指向链表的 <code>head</code>，<code>key.prev</code> 指向链表的 <code>tail</code></li>
</ul>
<p>☄ <strong>双指针技巧</strong></p>
<h4 id="141-环形链表"><a href="#141-环形链表" class="headerlink" title="141. 环形链表"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/linked-list-cycle/solution/2xing-python-by-knifezhu/">141. 环形链表</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode(object):</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">hasCycle</span>(<span class="params">self, head</span>):</span><br><span class="line">        slow = fast = head</span><br><span class="line">        <span class="keyword">while</span> fast <span class="keyword">and</span> fast.<span class="built_in">next</span>:</span><br><span class="line">            fast = fast.<span class="built_in">next</span>.<span class="built_in">next</span></span><br><span class="line">            slow = slow.<span class="built_in">next</span></span><br><span class="line">            <span class="keyword">if</span> slow == fast:</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">        <span class="keyword">return</span> <span class="literal">False</span></span><br></pre></td></tr></table></figure>
<ul>
<li>想象一下，有两个速度不同的跑步者。如果他们在直路上行驶，快跑者将首先到达目的地。但是，如果它们在圆形跑道上跑步，那么快跑者如果继续跑步就会追上慢跑者。这正是我们在链表中使用两个速度不同的指针时会遇到的情况：<ul>
<li>如果没有环，快指针将停在链表的末尾。</li>
<li>如果有环，快指针最终将与慢指针相遇。</li>
</ul>
</li>
<li>所以剩下的问题是：这两个指针的适当速度应该是多少？一个安全的选择是每次移动慢指针一步，而移动快指针两步。每一次迭代，快速指针将额外移动一步。如果环的长度为 M，经过 M 次迭代后，快指针肯定会多绕环一周，并赶上慢指针。<h4 id="142-环形链表-II"><a href="#142-环形链表-II" class="headerlink" title="142. 环形链表 II"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/linked-list-cycle-ii/">142. 环形链表 II</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">detectCycle</span>(<span class="params">self, head</span>):</span><br><span class="line">	slow = fast = head</span><br><span class="line">	<span class="keyword">while</span> fast <span class="keyword">and</span> fast.<span class="built_in">next</span>:</span><br><span class="line">	    fast = fast.<span class="built_in">next</span>.<span class="built_in">next</span></span><br><span class="line">	    slow = slow.<span class="built_in">next</span></span><br><span class="line">	    <span class="keyword">if</span> slow == fast:</span><br><span class="line">		<span class="keyword">break</span></span><br><span class="line">	<span class="keyword">else</span>:</span><br><span class="line">	    <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line">	<span class="keyword">while</span> head <span class="keyword">is</span> <span class="keyword">not</span> slow:</span><br><span class="line">	    head = head.<span class="built_in">next</span></span><br><span class="line">	    slow = slow.<span class="built_in">next</span></span><br><span class="line">	<span class="keyword">return</span> head</span><br></pre></td></tr></table></figure></li>
<li>设环的起始节点为 E，快慢指针从 head 出发，快指针速度为 2，设相交节点为 X，head 到 E 的距离为 H，E 到 X 的距离为 D，环的长度为 L，那么有：快指针走过的距离等于慢指针走过的距离加快指针多走的距离（多走了 n 圈的 L） <code>2(H + D) = H + D + nL</code>，因此可以推出 <code>H = nL - D</code>，这意味着如果我们让俩个慢指针一个从 head 出发，一个从 X 出发的话，他们一定会在节点 E 相遇  <figure class="highlight asciidoc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="code">	  _____</span></span><br><span class="line"><span class="code">	 /     \</span></span><br><span class="line">head<span class="emphasis">_____</span><span class="emphasis">_____</span><span class="emphasis">_E       \</span></span><br><span class="line"><span class="emphasis">	\       /</span></span><br><span class="line"><span class="emphasis">	 X_____</span>/ </span><br></pre></td></tr></table></figure>
<h4 id="160-相交链表"><a href="#160-相交链表" class="headerlink" title="160. 相交链表"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/intersection-of-two-linked-lists/">160. 相交链表</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode(object):</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">getIntersectionNode</span>(<span class="params">self, headA, headB</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        :type head1, head1: ListNode</span></span><br><span class="line"><span class="string">        :rtype: ListNode</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        a, b = (headA, headB) <span class="keyword">if</span> headA <span class="keyword">and</span> headB <span class="keyword">else</span> (<span class="literal">None</span>, <span class="literal">None</span>)</span><br><span class="line">        <span class="keyword">while</span> a != b: a, b = <span class="keyword">not</span> a <span class="keyword">and</span> headB <span class="keyword">or</span> a.<span class="built_in">next</span>, <span class="keyword">not</span> b <span class="keyword">and</span> headA <span class="keyword">or</span> b.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">return</span> a</span><br></pre></td></tr></table></figure></li>
<li>这题不支持 Python3 所以只能用 Python2 做了</li>
<li>把第一条链表的尾部接到第二条链表的开头，第二条接到第一条的开头，就能消除俩条链表的长度差，并在某一时刻在第一个交叉点相遇，或在走完俩条链表长度的时候同时为 None  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 假设有两条链表1→2→3→4和①→②→③，模拟一下算法流程 ↓</span></span><br><span class="line"></span><br><span class="line"><span class="number">1</span> → <span class="number">2</span> ↘  ↗ → <span class="number">4</span>                               <span class="number">1</span> → <span class="number">2</span> ↘  ↗ → <span class="number">4</span> → ① → → → <span class="number">3</span>(②) ❤ 相遇了</span><br><span class="line">① → → → <span class="number">3</span>(②) → ③   把<span class="number">4</span>接到①前面，把③接到<span class="number">1</span>前面   ① → → → <span class="number">3</span>(②) → ③ → <span class="number">1</span> → <span class="number">2</span> ↗     若非相交链表则同时走到<span class="literal">None</span></span><br></pre></td></tr></table></figure>
<h4 id="19-删除链表的倒数第N个节点"><a href="#19-删除链表的倒数第N个节点" class="headerlink" title="19. 删除链表的倒数第N个节点"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/">19. 删除链表的倒数第N个节点</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">removeNthFromEnd</span>(<span class="params">self, head: ListNode, n: <span class="built_in">int</span></span>) -&gt; ListNode:</span><br><span class="line">        link = []</span><br><span class="line">        <span class="keyword">while</span> head:</span><br><span class="line">            link.append(head)</span><br><span class="line">            head = head.<span class="built_in">next</span></span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> n != <span class="built_in">len</span>(link):</span><br><span class="line">            link[-n - <span class="number">1</span>].<span class="built_in">next</span> = link[-n].<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">del</span> link[-n]</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> link <span class="keyword">and</span> link[<span class="number">0</span>]</span><br></pre></td></tr></table></figure></li>
<li>列表记录整个链表，换成队列记录最后几个可以把空间复杂度压到 $O(1)$</li>
</ul>
<p>☄ <strong>经典问题</strong></p>
<h4 id="206-反转链表"><a href="#206-反转链表" class="headerlink" title="206. 反转链表"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/reverse-linked-list/">206. 反转链表</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">reverseList</span>(<span class="params">self, head: ListNode</span>) -&gt; ListNode:</span><br><span class="line">        p = <span class="literal">None</span></span><br><span class="line">        <span class="keyword">while</span> head:</span><br><span class="line">            head.<span class="built_in">next</span>, head, p = p, head.<span class="built_in">next</span>, head</span><br><span class="line">        <span class="keyword">return</span> p</span><br></pre></td></tr></table></figure>
<ul>
<li>遍历一遍链表，每次都把相邻节点的指向反转（A→B 变成 A←B）<h4 id="203-移除链表元素"><a href="#203-移除链表元素" class="headerlink" title="203. 移除链表元素"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/remove-linked-list-elements/submissions/">203. 移除链表元素</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">removeElements</span>(<span class="params">self, head: ListNode, val: <span class="built_in">int</span></span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">while</span> head <span class="keyword">and</span> head.val == val:</span><br><span class="line">            head = head.<span class="built_in">next</span></span><br><span class="line">        pre, cur = head, head <span class="keyword">and</span> head.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">while</span> cur:</span><br><span class="line">            <span class="keyword">if</span> cur.val == val:</span><br><span class="line">                pre.<span class="built_in">next</span> = cur = cur.<span class="built_in">next</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                pre, cur = cur, cur.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">return</span> head</span><br></pre></td></tr></table></figure></li>
<li>第一个 while 用于找到应该返回的链表头（应该跳过所有特殊 val 的节点）</li>
<li>第二个 while 用于把前一个节点指针接到下一个节点（如果当前节点值为 val）<h4 id="328-奇偶链表"><a href="#328-奇偶链表" class="headerlink" title="328. 奇偶链表"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/odd-even-linked-list/solution/">328. 奇偶链表</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">oddEvenList</span>(<span class="params">self, head: ListNode</span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> head <span class="keyword">or</span> <span class="keyword">not</span> head.<span class="built_in">next</span>: <span class="keyword">return</span> head</span><br><span class="line">        r, odd, p, head = head, head, head.<span class="built_in">next</span>, head.<span class="built_in">next</span>.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">while</span> head:</span><br><span class="line">            odd.<span class="built_in">next</span>, head.<span class="built_in">next</span>, p.<span class="built_in">next</span> = head, odd.<span class="built_in">next</span>, head.<span class="built_in">next</span></span><br><span class="line">            p, odd, head = p.<span class="built_in">next</span>, head, p.<span class="built_in">next</span> <span class="keyword">and</span> p.<span class="built_in">next</span>.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>odd 记录上一个奇数位节点，p 记录前一个节点</li>
<li>从第3个位置开始循环，每次都把当前节点接到 odd 后面，然后跳到下一个奇数位节点继续循环<h4 id="234-回文链表"><a href="#234-回文链表" class="headerlink" title="234. 回文链表"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/palindrome-linked-list/submissions/">234. 回文链表</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isPalindrome</span>(<span class="params">self, head: ListNode</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        s, f, p = head, head, <span class="literal">None</span></span><br><span class="line">        <span class="keyword">while</span> f <span class="keyword">and</span> f.<span class="built_in">next</span>:</span><br><span class="line">            s.<span class="built_in">next</span>, p, s, f = p, s, s.<span class="built_in">next</span>, f.<span class="built_in">next</span>.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">if</span> f: s = s <span class="keyword">and</span> s.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">while</span> s <span class="keyword">and</span> p <span class="keyword">and</span> s.val == p.val:</span><br><span class="line">            p, s = p.<span class="built_in">next</span>, s.<span class="built_in">next</span></span><br><span class="line">        <span class="keyword">return</span> s == p == <span class="literal">None</span></span><br></pre></td></tr></table></figure></li>
<li>f 记录快指针，每次走倆步，s 记录慢指针，每次走一步，p 记录 s 的前一个节点</li>
<li>首先使用快慢指针找到中点，第一个 while 停止时如果链表长度为奇数，s 为中点；否则 f 为 None，s 为右半部分的第一个节点</li>
<li>若链表长度为奇数，s 前进一步，然后 p 和 s 往俩个方向同时遍历比对是否回文</li>
</ul>
<p>☄ <strong>双链表</strong></p>
<ul>
<li>【设计链表】 同上</li>
</ul>
<p>☄ <strong>小结</strong></p>
<h4 id="21-合并两个有序链表"><a href="#21-合并两个有序链表" class="headerlink" title="21. 合并两个有序链表"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/linked-list/197/conclusion/762/">21. 合并两个有序链表</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">mergeTwoLists</span>(<span class="params">self, l1: ListNode, l2: ListNode</span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">if</span> l1 <span class="keyword">and</span> l2:</span><br><span class="line">            <span class="keyword">if</span> l1.val &gt; l2.val: l1, l2 = l2, l1</span><br><span class="line">            l1.<span class="built_in">next</span> = self.mergeTwoLists(l1.<span class="built_in">next</span>, l2)</span><br><span class="line">        <span class="keyword">return</span> l1 <span class="keyword">or</span> l2</span><br></pre></td></tr></table></figure>
<ul>
<li>and：如果 and 前面的表达式已经为 False，那么 and 之后的表达式将被 <strong>跳过</strong>，返回左表达式结果</li>
<li>or：如果 or 前面的表达式已经为 True，那么 or 之后的表达式将被跳过，直接返回左表达式的结果</li>
<li>例子：<code>[] and 7</code> 等于 <code>[]</code></li>
<li>判断 l1 或 l2 中是否有一个节点为空，如果存在，那么我们只需要把不为空的节点接到链表后面即可</li>
<li>对 l1 和 l2 重新赋值，使得 l1 指向比较小的那个节点对象</li>
<li>修改 l1 的 next 属性为递归函数返回值</li>
<li>返回 l1，注意：如果 l1 和 l2 同时为 None，此时递归停止返回 None</li>
<li>时间复杂度：$O(n)$ 空间复杂度：【考虑递归开栈】$O(n)$【不考虑】$O(1)$<h4 id="2-两数相加"><a href="#2-两数相加" class="headerlink" title="2. 两数相加"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/add-two-numbers/">2. 两数相加</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">addTwoNumbers</span>(<span class="params">self, l1: ListNode, l2: ListNode, carry=<span class="number">0</span></span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> (l1 <span class="keyword">or</span> l2): <span class="keyword">return</span> ListNode(<span class="number">1</span>) <span class="keyword">if</span> carry <span class="keyword">else</span> <span class="literal">None</span></span><br><span class="line">        l1, l2 = l1 <span class="keyword">or</span> ListNode(<span class="number">0</span>), l2 <span class="keyword">or</span> ListNode(<span class="number">0</span>)</span><br><span class="line">        val = l1.val + l2.val + carry</span><br><span class="line">        l1.val, l1.<span class="built_in">next</span> = val % <span class="number">10</span>, self.addTwoNumbers(l1.<span class="built_in">next</span>, l2.<span class="built_in">next</span>, val &gt; <span class="number">9</span>)</span><br><span class="line">        <span class="keyword">return</span> l1</span><br></pre></td></tr></table></figure></li>
<li><code>int(True)</code> 等于 1</li>
<li><code>None or 7</code> 等于 7</li>
<li>用 <code>carry</code> 记录是否应该进位<h4 id="430-扁平化多级双向链表"><a href="#430-扁平化多级双向链表" class="headerlink" title="430. 扁平化多级双向链表"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/flatten-a-multilevel-doubly-linked-list/submissions/">430. 扁平化多级双向链表</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string"># Definition for a Node.</span></span><br><span class="line"><span class="string">class Node:</span></span><br><span class="line"><span class="string">    def __init__(self, val, prev, next, child):</span></span><br><span class="line"><span class="string">        self.val = val</span></span><br><span class="line"><span class="string">        self.prev = prev</span></span><br><span class="line"><span class="string">        self.next = next</span></span><br><span class="line"><span class="string">        self.child = child</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">flatten</span>(<span class="params">self, head: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="string">&#x27;Node&#x27;</span>:</span><br><span class="line">        stack = [head] <span class="keyword">if</span> head <span class="keyword">else</span> []</span><br><span class="line">        </span><br><span class="line">        p = <span class="literal">None</span></span><br><span class="line">        <span class="keyword">while</span> stack:</span><br><span class="line">            node = stack.pop()</span><br><span class="line">            <span class="keyword">if</span> node.<span class="built_in">next</span>:</span><br><span class="line">                stack.append(node.<span class="built_in">next</span>)</span><br><span class="line">            <span class="keyword">if</span> node.child:</span><br><span class="line">                stack.append(node.child)</span><br><span class="line">            <span class="keyword">if</span> p:</span><br><span class="line">                p.<span class="built_in">next</span> = node</span><br><span class="line">                node.prev = p</span><br><span class="line">                p.child = node.child = <span class="literal">None</span></span><br><span class="line">            p = node</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> head</span><br></pre></td></tr></table></figure></li>
<li>常规 DFS 遍历<h4 id="138-复制带随机指针的链表"><a href="#138-复制带随机指针的链表" class="headerlink" title="138. 复制带随机指针的链表"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/copy-list-with-random-pointer/submissions/">138. 复制带随机指针的链表</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string"># Definition for a Node.</span></span><br><span class="line"><span class="string">class Node:</span></span><br><span class="line"><span class="string">    def __init__(self, val, next, random):</span></span><br><span class="line"><span class="string">        self.val = val</span></span><br><span class="line"><span class="string">        self.next = next</span></span><br><span class="line"><span class="string">        self.random = random</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">copyRandomList</span>(<span class="params">self, head: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="string">&#x27;Node&#x27;</span>:</span><br><span class="line">        d, node = &#123;<span class="literal">None</span>: <span class="literal">None</span>&#125;, head</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">while</span> node:</span><br><span class="line">            d[node] = Node(node.val, <span class="literal">None</span>, <span class="literal">None</span>)</span><br><span class="line">            node = node.<span class="built_in">next</span></span><br><span class="line">        </span><br><span class="line">        node = head</span><br><span class="line">        <span class="keyword">while</span> node:</span><br><span class="line">            d[node].<span class="built_in">next</span> = d[node.<span class="built_in">next</span>]</span><br><span class="line">            d[node].random = d[node.random]</span><br><span class="line">            node = node.<span class="built_in">next</span></span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> d[head]</span><br></pre></td></tr></table></figure></li>
<li>难点在于创建节点的时候需要指向未创建的节点</li>
<li>遍历俩遍可有效解决，用字典记录对应的节点，然后依靠原来的链表来遍历新链表，第一次遍历未知的节点置 None，第二次再把已经创建的节点改上去</li>
<li>链表也是图，133题的dfs解法同样可行<h4 id="61-旋转链表"><a href="#61-旋转链表" class="headerlink" title="61. 旋转链表"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/rotate-list/">61. 旋转链表</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">rotateRight</span>(<span class="params">self, head: ListNode, k: <span class="built_in">int</span></span>) -&gt; ListNode:</span><br><span class="line">        l = []</span><br><span class="line">        <span class="keyword">while</span> head:</span><br><span class="line">            l.append(head)</span><br><span class="line">            head = head.<span class="built_in">next</span></span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> l:</span><br><span class="line">            l[-<span class="number">1</span>].<span class="built_in">next</span>, l[-<span class="number">1</span> - k % <span class="built_in">len</span>(l)].<span class="built_in">next</span> = l[<span class="number">0</span>], <span class="literal">None</span></span><br><span class="line">            <span class="keyword">return</span> l[- k % <span class="built_in">len</span>(l)]</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> <span class="literal">None</span></span><br></pre></td></tr></table></figure></li>
<li>用 list 记录链表，把链表当作环，修补原来的切断口，创造新的缺口（k）<h3 id="🌠-哈希表"><a href="#🌠-哈希表" class="headerlink" title="🌠 哈希表"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/queue-stack/">🌠 哈希表</a></h3></li>
<li>【知识卡片】在<strong>哈希表</strong>中，我们可以利用哈希函数快速访问到数组中的目标数据。如果发生哈希 冲突，就使用链表进行存储。这样一来，不管数据量为多少，我们都能够灵活应对。 如果数组的空间太小，使用哈希表的时候就容易发生冲突，线性查找的使用频率也会更高；反过来，如果数组的空间太大，就会出现很多空箱子，造成内存的浪费。因此， 给数组设定合适的空间非常重要。</li>
</ul>
<p>☄ <strong>设计哈希表</strong></p>
<h4 id="705-设计哈希集合"><a href="#705-设计哈希集合" class="headerlink" title="705. 设计哈希集合"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/design-hashset/">705. 设计哈希集合</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Node</span>:</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, val, nex</span>):</span><br><span class="line">        self.val = val</span><br><span class="line">        self.nex = nex</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyHashSet</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Initialize your data structure here.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.size = <span class="number">1000</span></span><br><span class="line">        self.h = [Node(<span class="literal">None</span>, <span class="literal">None</span>) <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(self.size)]</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">add</span>(<span class="params">self, key: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        p = self.h[key % self.size]</span><br><span class="line">        node = p.nex</span><br><span class="line">        <span class="keyword">while</span> node:</span><br><span class="line">            <span class="keyword">if</span> node.val == key:</span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">            p = node</span><br><span class="line">            node = node.nex</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            p.nex = Node(key, <span class="literal">None</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">remove</span>(<span class="params">self, key: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        p = self.h[key % self.size]</span><br><span class="line">        node = p.nex</span><br><span class="line">        <span class="keyword">while</span> node:</span><br><span class="line">            <span class="keyword">if</span> node.val == key:</span><br><span class="line">                p.nex = node.nex</span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">            p = node</span><br><span class="line">            node = node.nex</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">contains</span>(<span class="params">self, key: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Returns true if this set contains the specified element</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        node = self.h[key % self.size]</span><br><span class="line">        <span class="keyword">while</span> node:</span><br><span class="line">            <span class="keyword">if</span> node.val == key:</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">            node = node.nex</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your MyHashSet object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = MyHashSet()</span></span><br><span class="line"><span class="comment"># obj.add(key)</span></span><br><span class="line"><span class="comment"># obj.remove(key)</span></span><br><span class="line"><span class="comment"># param_3 = obj.contains(key)</span></span><br></pre></td></tr></table></figure>
<ul>
<li>在存储数据的过程中，如果发生冲突，可以利用链表在已有数据的后面插入新数据 来解决冲突。这种方法被称为“链地址法”<h4 id="706-设计哈希映射"><a href="#706-设计哈希映射" class="headerlink" title="706. 设计哈希映射"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/design-hashmap/submissions/">706. 设计哈希映射</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Node</span>:</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, key=<span class="literal">None</span>, val=<span class="literal">None</span>, nex=<span class="literal">None</span></span>):</span><br><span class="line">        self.key = key</span><br><span class="line">        self.val = val</span><br><span class="line">        self.nex = nex</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyHashMap</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Initialize your data structure here.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.size = <span class="number">1000</span></span><br><span class="line">        self.h = [Node() <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(self.size)]</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">put</span>(<span class="params">self, key: <span class="built_in">int</span>, value: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        value will always be non-negative.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        p = self.h[key % self.size]</span><br><span class="line">        c = p.nex</span><br><span class="line">        <span class="keyword">while</span> c:</span><br><span class="line">            <span class="keyword">if</span> c.key == key:</span><br><span class="line">                c.val = value</span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">            p = c</span><br><span class="line">            c = c.nex</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            p.nex = Node(key, value)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">get</span>(<span class="params">self, key: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        c = self.h[key % self.size]</span><br><span class="line">        <span class="keyword">while</span> c:</span><br><span class="line">            <span class="keyword">if</span> c.key == key:</span><br><span class="line">                <span class="keyword">return</span> c.val</span><br><span class="line">            c = c.nex</span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">remove</span>(<span class="params">self, key: <span class="built_in">int</span></span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Removes the mapping of the specified value key if this map contains a mapping for the key</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        p = self.h[key % self.size]</span><br><span class="line">        c = p.nex</span><br><span class="line">        <span class="keyword">while</span> c:</span><br><span class="line">            <span class="keyword">if</span> c.key == key:</span><br><span class="line">                p.nex = c.nex</span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">            p = c</span><br><span class="line">            c = c.nex</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your MyHashMap object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = MyHashMap()</span></span><br><span class="line"><span class="comment"># obj.put(key,value)</span></span><br><span class="line"><span class="comment"># param_2 = obj.get(key)</span></span><br><span class="line"><span class="comment"># obj.remove(key)</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>☄ <strong>实际应用 - 哈希集合</strong></p>
<h4 id="217-存在重复元素"><a href="#217-存在重复元素" class="headerlink" title="217. 存在重复元素"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/contains-duplicate/">217. 存在重复元素</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">containsDuplicate</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">len</span>(<span class="built_in">set</span>(nums)) != <span class="built_in">len</span>(nums)</span><br></pre></td></tr></table></figure>
<h4 id="136-只出现一次的数字"><a href="#136-只出现一次的数字" class="headerlink" title="136. 只出现一次的数字"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/single-number/">136. 只出现一次的数字</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">singleNumber</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">from</span> functools <span class="keyword">import</span> reduce</span><br><span class="line">        <span class="keyword">return</span> reduce(<span class="built_in">int</span>.__xor__, nums)</span><br></pre></td></tr></table></figure>
<ul>
<li>这里用到了异或（xor），相同的数字异或后为0，0异或任何数都等于那个数，用reduce在列表所有元素之间使用异或^，那么留下的就是那个单独的数字了。<h4 id="349-两个数组的交集"><a href="#349-两个数组的交集" class="headerlink" title="349. 两个数组的交集"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/intersection-of-two-arrays/submissions/">349. 两个数组的交集</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">intersection</span>(<span class="params">self, nums1: <span class="type">List</span>[<span class="built_in">int</span>], nums2: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> [*<span class="built_in">set</span>(nums1) &amp; <span class="built_in">set</span>(nums2)]</span><br></pre></td></tr></table></figure></li>
<li>经过 set 之后，重复的元素被删除</li>
<li>与运算对于集合来说就是求交集<h4 id="202-快乐数"><a href="#202-快乐数" class="headerlink" title="202. 快乐数"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/happy-number/">202. 快乐数</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isHappy</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        seen = &#123;<span class="number">1</span>&#125;</span><br><span class="line">        <span class="keyword">while</span> n <span class="keyword">not</span> <span class="keyword">in</span> seen:</span><br><span class="line">            seen.add(n)</span><br><span class="line">            n = <span class="built_in">sum</span>(<span class="built_in">int</span>(i) ** <span class="number">2</span> <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">str</span>(n))</span><br><span class="line">        <span class="keyword">return</span> n == <span class="number">1</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>☄ <strong>实际应用 - 哈希映射</strong></p>
<h4 id="1-两数之和"><a href="#1-两数之和" class="headerlink" title="1. 两数之和"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/two-sum/">1. 两数之和</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">twoSum</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], target: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">	d = &#123;&#125;</span><br><span class="line">	<span class="keyword">for</span> i, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(nums): </span><br><span class="line">	    <span class="keyword">if</span> n <span class="keyword">in</span> d: <span class="keyword">return</span> [d[n], i]</span><br><span class="line">	    d[target-n] = i</span><br></pre></td></tr></table></figure>
<ul>
<li>$O(N)$时间效率的快速解法，用字典记录 ｛需要的值:当前索引｝<h4 id="205-同构字符串"><a href="#205-同构字符串" class="headerlink" title="205. 同构字符串"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/isomorphic-strings/solution/1-xing-python-by-knifezhu-5/">205. 同构字符串</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isIsomorphic</span>(<span class="params">self, s: <span class="built_in">str</span>, t: <span class="built_in">str</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">return</span> [*<span class="built_in">map</span>(s.index, s)] == [*<span class="built_in">map</span>(t.index, t)]</span><br></pre></td></tr></table></figure></li>
<li>同构代表两个字符串中每个位置上字符在自身第一次出现的索引相同<h4 id="599-两个列表的最小索引总和"><a href="#599-两个列表的最小索引总和" class="headerlink" title="599. 两个列表的最小索引总和"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/minimum-index-sum-of-two-lists/">599. 两个列表的最小索引总和</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findRestaurant</span>(<span class="params">self, list1: <span class="type">List</span>[<span class="built_in">str</span>], list2: <span class="type">List</span>[<span class="built_in">str</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">str</span>]:</span><br><span class="line">        d = &#123;x: list1.index(x) + list2.index(x) <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">set</span>(list1) &amp; <span class="built_in">set</span>(list2)&#125;</span><br><span class="line">        <span class="keyword">return</span> [x <span class="keyword">for</span> x <span class="keyword">in</span> d <span class="keyword">if</span> d[x] == <span class="built_in">min</span>(d.values())]</span><br></pre></td></tr></table></figure></li>
<li>使用字典记录｛共同喜欢的商店：索引和｝，返回索引和并列最小的商店名<h4 id="387-字符串中的第一个唯一字符"><a href="#387-字符串中的第一个唯一字符" class="headerlink" title="387. 字符串中的第一个唯一字符"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/first-unique-character-in-a-string/submissions/">387. 字符串中的第一个唯一字符</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">firstUniqChar</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        d = &#123;c: s.count(c) <span class="keyword">for</span> c <span class="keyword">in</span> <span class="built_in">set</span>(s)&#125;</span><br><span class="line">        <span class="keyword">for</span> i, c <span class="keyword">in</span> <span class="built_in">enumerate</span>(s):</span><br><span class="line">            <span class="keyword">if</span> d[c] == <span class="number">1</span>:</span><br><span class="line">                <span class="keyword">return</span> i</span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span></span><br></pre></td></tr></table></figure></li>
<li>首先用字典 d 储存｛字符：出现次数｝，注意这里的字符来自 set，为了避免重复操作，防止TLE</li>
<li>然后遍历 s 寻找出现次数为 1 的第一个字符索引，不存在则返回 -1<h4 id="350-两个数组的交集-II"><a href="#350-两个数组的交集-II" class="headerlink" title="350. 两个数组的交集 II"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/">350. 两个数组的交集 II</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">intersect</span>(<span class="params">self, nums1: <span class="type">List</span>[<span class="built_in">int</span>], nums2: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> [*(collections.Counter(nums1) &amp; collections.Counter(nums2)).elements()]</span><br></pre></td></tr></table></figure></li>
<li>对于两个 Counter 对象，与操作意味着取两者都有的key, value取小的那一个</li>
<li>参考：<a target="_blank" rel="noopener" href="https://www.cnblogs.com/nisen/p/6052895.html">Python Counter 计数工具</a><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">intersect</span>(<span class="params">self, nums1: <span class="type">List</span>[<span class="built_in">int</span>], nums2: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        nums1.sort()</span><br><span class="line">        nums2.sort()</span><br><span class="line">        r = []</span><br><span class="line">        i = j = <span class="number">0</span></span><br><span class="line">        <span class="keyword">while</span> i &lt; <span class="built_in">len</span>(nums1) <span class="keyword">and</span> j &lt; <span class="built_in">len</span>(nums2):</span><br><span class="line">            <span class="keyword">if</span> nums1[i] == nums2[j]:</span><br><span class="line">                r.append(nums1[i])</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">                j += <span class="number">1</span></span><br><span class="line">            <span class="keyword">elif</span> nums1[i] &lt; nums2[j]:</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                j += <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>进阶解法 ↑</li>
<li>使用双指针将两个列表中共同的元素抠下来，因为已经排序，所以遇到不同元素时数值小的那个列表的指针向前移动<h4 id="219-存在重复元素-II"><a href="#219-存在重复元素-II" class="headerlink" title="219. 存在重复元素 II"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/contains-duplicate-ii/">219. 存在重复元素 II</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">containsNearbyDuplicate</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], k: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        r = <span class="built_in">float</span>(<span class="string">&#x27;inf&#x27;</span>)</span><br><span class="line">        d = &#123;&#125;</span><br><span class="line">        <span class="keyword">for</span> i, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(nums):</span><br><span class="line">            r = <span class="built_in">min</span>(r, i - d.get(n, <span class="built_in">float</span>(<span class="string">&#x27;-inf&#x27;</span>)))</span><br><span class="line">            d[n] = i</span><br><span class="line">        <span class="keyword">return</span> r &lt;= k</span><br></pre></td></tr></table></figure></li>
<li>本题题目有误，实际意思是找同数字最小间隔，若不超过 k 则满足条件</li>
<li>遍历列表，每次都比对最小间隔，并更新哈希表索引，当前位置往左的最小间隔一定是与上一次同数字出现的索引的距离</li>
</ul>
<p>☄ <strong>实际应用 - 设计键</strong></p>
<h4 id="49-字母异位词分组"><a href="#49-字母异位词分组" class="headerlink" title="49. 字母异位词分组"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/group-anagrams/">49. 字母异位词分组</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">groupAnagrams</span>(<span class="params">self, strs: <span class="type">List</span>[<span class="built_in">str</span>]</span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">str</span>]]:</span><br><span class="line">        d = collections.defaultdict(<span class="built_in">list</span>)</span><br><span class="line">        <span class="keyword">for</span> s <span class="keyword">in</span> strs:</span><br><span class="line">	    d[<span class="string">&#x27;&#x27;</span>.join(<span class="built_in">sorted</span>(s))].append(s)</span><br><span class="line">        <span class="keyword">return</span> [*d.values()]</span><br></pre></td></tr></table></figure>
<ul>
<li>以排序后的单词为 key，将所有字符串分组<h4 id="36-有效的数独"><a href="#36-有效的数独" class="headerlink" title="36. 有效的数独"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/valid-sudoku/">36. 有效的数独</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isValidSudoku</span>(<span class="params">self, board: <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">str</span>]]</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        row, col, pal = <span class="built_in">eval</span>(<span class="string">&#x27;,&#x27;</span>.join([<span class="string">&#x27;[[0] * 9 for _ in range(9)]&#x27;</span>] * <span class="number">3</span>))</span><br><span class="line">        <span class="keyword">for</span> i, r <span class="keyword">in</span> <span class="built_in">enumerate</span>(board):</span><br><span class="line">            <span class="keyword">for</span> j, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(r):</span><br><span class="line">                <span class="keyword">if</span> n == <span class="string">&#x27;.&#x27;</span>: <span class="keyword">continue</span></span><br><span class="line">                n = <span class="built_in">int</span>(n) - <span class="number">1</span></span><br><span class="line">                <span class="keyword">if</span> row[i][n] <span class="keyword">or</span> col[j][n] <span class="keyword">or</span> pal[i // <span class="number">3</span> * <span class="number">3</span> + j // <span class="number">3</span>][n]: <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">                row[i][n] = col[j][n] = pal[i // <span class="number">3</span> * <span class="number">3</span> + j // <span class="number">3</span>][n] = <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> <span class="literal">True</span></span><br></pre></td></tr></table></figure></li>
<li>使用 3 个二维矩阵记录某数字是否已经在特定区域出现过，如第 1 行，第 4 列对于 row[0], col[3], pal[1] 区域，每个区域包含 9 个数值，用以记录其 索引 + 1 是否在改区域出现过<h4 id="652-寻找重复的子树"><a href="#652-寻找重复的子树" class="headerlink" title="652. 寻找重复的子树"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-duplicate-subtrees/">652. 寻找重复的子树</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findDuplicateSubtrees</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[TreeNode]:</span><br><span class="line">        d, r = &#123;&#125;, []</span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">dfs</span>(<span class="params">root</span>):</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> root: <span class="keyword">return</span> <span class="string">&#x27;#&#x27;</span></span><br><span class="line">            s = <span class="string">&#x27;# &#x27;</span> + <span class="string">&#x27; &#x27;</span>.join((<span class="built_in">str</span>(root.val), dfs(root.left), dfs(root.right)))</span><br><span class="line">            d[s] = d.get(s, <span class="number">0</span>) + <span class="number">1</span></span><br><span class="line">            <span class="keyword">if</span> d[s] == <span class="number">2</span>: r.append(root)</span><br><span class="line">            <span class="keyword">return</span> s</span><br><span class="line">        dfs(root)</span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>使用字典 d 记录｛子树结构：[root1，root2，……]｝</li>
</ul>
<p>☄ <strong>小结</strong></p>
<h4 id="771-宝石与石头"><a href="#771-宝石与石头" class="headerlink" title="771. 宝石与石头"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/jewels-and-stones/">771. 宝石与石头</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">numJewelsInStones</span>(<span class="params">self, J: <span class="built_in">str</span>, S: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        j = <span class="built_in">set</span>(J)</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sum</span>(<span class="built_in">bool</span>(s <span class="keyword">in</span> j) <span class="keyword">for</span> s <span class="keyword">in</span> S)</span><br></pre></td></tr></table></figure>
<ul>
<li>set 的 in 操作时间复杂度为 O(1)<h4 id="3-无重复字符的最长子串"><a href="#3-无重复字符的最长子串" class="headerlink" title="3. 无重复字符的最长子串"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/submissions/">3. 无重复字符的最长子串</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">lengthOfLongestSubstring</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        i, r, d = -<span class="number">1</span>, <span class="number">0</span>, &#123;&#125;</span><br><span class="line">        <span class="keyword">for</span> j, c <span class="keyword">in</span> <span class="built_in">enumerate</span>(s):</span><br><span class="line">            i = <span class="built_in">max</span>(i, d.get(c, -<span class="number">1</span>))</span><br><span class="line">            r = <span class="built_in">max</span>(r, j - i)</span><br><span class="line">            d[c] = j</span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>双指针滑动窗口，i 代表窗口起始位置，j 代表窗口结束位置，r 记录最优结果，d 记录所有字符最后出现的位置（对于 j 遍历来说）<h4 id="454-四数相加-II"><a href="#454-四数相加-II" class="headerlink" title="454. 四数相加 II"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/4sum-ii/comments/">454. 四数相加 II</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">fourSumCount</span>(<span class="params">self, A: <span class="type">List</span>[<span class="built_in">int</span>], B: <span class="type">List</span>[<span class="built_in">int</span>], C: <span class="type">List</span>[<span class="built_in">int</span>], D: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        dic = &#123;&#125;</span><br><span class="line">        <span class="keyword">for</span> a <span class="keyword">in</span> A:</span><br><span class="line">            <span class="keyword">for</span> b <span class="keyword">in</span> B:</span><br><span class="line">                dic[a + b] = dic.get(a + b, <span class="number">0</span>) + <span class="number">1</span></span><br><span class="line"></span><br><span class="line">        r = <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> c <span class="keyword">in</span> C:</span><br><span class="line">            <span class="keyword">for</span> d <span class="keyword">in</span> D:</span><br><span class="line">                r += dic.get(- c - d, <span class="number">0</span>)</span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>思路同第一题 TWO SUM 的 O(N) 字典解法，记录需要的值<h4 id="347-前K个高频元素"><a href="#347-前K个高频元素" class="headerlink" title="347. 前K个高频元素"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/top-k-frequent-elements/">347. 前K个高频元素</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">topKFrequent</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], k: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        d = &#123;n: <span class="number">0</span> <span class="keyword">for</span> n <span class="keyword">in</span> nums&#125;</span><br><span class="line">        <span class="keyword">for</span> n <span class="keyword">in</span> nums:</span><br><span class="line">            d[n] += <span class="number">1</span></span><br><span class="line">        </span><br><span class="line">        r = []</span><br><span class="line">        <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(k):</span><br><span class="line">            n = <span class="built_in">max</span>(d, key=d.get)</span><br><span class="line">            r.append(n)</span><br><span class="line">            d[n] = -<span class="number">1</span></span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>时间复杂度 O(N)，空间复杂度 O(N)</li>
<li>使用字典 d 记录｛数字：出现次数｝</li>
<li>循环 k 次分别取出最大值放入结果列表 r<h4 id="380-常数时间插入、删除和获取随机元素"><a href="#380-常数时间插入、删除和获取随机元素" class="headerlink" title="380. 常数时间插入、删除和获取随机元素"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/insert-delete-getrandom-o1/">380. 常数时间插入、删除和获取随机元素</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">RandomizedSet</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Initialize your data structure here.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        self.d = &#123;&#125;</span><br><span class="line">        self.l = []</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">insert</span>(<span class="params">self, val: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Inserts a value to the set. Returns true if the set did not already contain the specified element.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">if</span> val <span class="keyword">in</span> self.d:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            self.d[val] = <span class="built_in">len</span>(self.l)</span><br><span class="line">            self.l.append(val)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">remove</span>(<span class="params">self, val: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Removes a value from the set. Returns true if the set contained the specified element.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">if</span> val <span class="keyword">in</span> self.d:</span><br><span class="line">            self.d[self.l[-<span class="number">1</span>]] = self.d[val]</span><br><span class="line">            self.l[self.d.pop(val)] = self.l[-<span class="number">1</span>]</span><br><span class="line">            self.l.pop()</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">getRandom</span>(<span class="params">self</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Get a random element from the set.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> self.l[random.randint(<span class="number">0</span>, <span class="built_in">len</span>(self.l) - <span class="number">1</span>)]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your RandomizedSet object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = RandomizedSet()</span></span><br><span class="line"><span class="comment"># param_1 = obj.insert(val)</span></span><br><span class="line"><span class="comment"># param_2 = obj.remove(val)</span></span><br><span class="line"><span class="comment"># param_3 = obj.getRandom()</span></span><br></pre></td></tr></table></figure></li>
<li>O(1)解法，组合使用哈希表和数组</li>
<li>插入时：用哈希表来判断是否已存在O(1)，数组末尾增加一个元素O(1)，哈希表记录｛值：索引｝O(1)</li>
<li>删除时：用哈希表来定位O(1)，把数组最后一个元素取下来顶替被删除元素位置O(1)，更新哈希表O(1)</li>
<li>取随机数时：随机从数组里面挑一个O(1)<h3 id="🌠-二分查找"><a href="#🌠-二分查找" class="headerlink" title="🌠 二分查找"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/linked-list/">🌠 二分查找</a></h3></li>
<li>【知识卡片】二分查找利用已排好序的数组，每一次查找都可以将查找范围减半。查找范围内只剩一个数据时查找结束。数据量为 n 的数组，将其长度减半 log2n 次后，其中便只剩一个数据了。也就是说，在二分查找中重复执行“将目标数据和数组中间的数据进行比较后将查找范围减半”的操作 log2n 次后，就能找到目标数据（若没找到则可以得出数据不存在的结论），因此它的时间复杂度为 O(logn)</li>
<li>💡【一般思路】什么时候应该使用二分搜索？怎么样使用？<ul>
<li><ol>
<li>在一个已知的范围内寻找答案</li>
</ol>
</li>
<li><ol>
<li>该范围集合有序</li>
</ol>
</li>
<li><ol>
<li>一般来说题目要求时间复杂度为 logN 就应该联想到二分搜索</li>
</ol>
</li>
<li><ol>
<li>如果把搜索范围看成一个函数的定义域，当我们拿到 x 的时候应该通过 f(x) 在整个函数中的特点决定 target 的大致位置</li>
</ol>
</li>
</ul>
</li>
<li>🌪【常见题型】<ul>
<li><ol>
<li>目标匹配类：<a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/guess-number-higher-or-lower/">374. 猜数字大小</a></li>
</ol>
</li>
<li><ol>
<li>邻居对比类：<a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-peak-element/">162. 寻找峰值</a></li>
</ol>
</li>
<li><ol>
<li>枚举试错类：第 K 个满足条件的值（此类题目范围一般比较隐晦，需要自己确定，然后通过在范围内枚举试错的方法确定 target 位置），例如 <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-k-th-smallest-pair-distance/">719. 找出第 k 小的距离对</a></li>
</ol>
</li>
</ul>
</li>
<li>【套路A】  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">self.__class__.__getitem__ = <span class="keyword">lambda</span> self, x: 向左搜索的条件（不包括target）</span><br><span class="line">寻找的索引 = bisect.bisect_left(self, <span class="literal">True</span>, <span class="number">0</span>, <span class="built_in">len</span>(nums)) - <span class="number">1</span></span><br></pre></td></tr></table></figure>
<ul>
<li>python 中 bisect 模块针对的是 list, 如果直接构造 list，时间复杂度为 O(N)，因此我们修改当前类的魔法方法伪造 list</li>
<li>bisect.left(用于比较的数组，搜索的值，起始范围(包括)，终止范围(不包括))：返回应该插入的位置</li>
</ul>
</li>
<li>【套路B】  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">self.__class__.__getitem__ = <span class="keyword">lambda</span> self, x: 向左搜索的条件（包括target）</span><br><span class="line">寻找的索引 = bisect.bisect_left(self, <span class="literal">True</span>, <span class="number">0</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span>)</span><br></pre></td></tr></table></figure>
<ul>
<li>搜索范围为 $[0,\;len(nums) - 1]$，注意此处为闭区间</li>
</ul>
</li>
<li>【非内置公式A】  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">二分查找二岔模板</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], target: <span class="built_in">int</span></span>):</span><br><span class="line">	l, h = <span class="number">0</span>, <span class="built_in">len</span>(nums)</span><br><span class="line">	<span class="keyword">while</span> l &lt; h:</span><br><span class="line">	    m = (l + h) // <span class="number">2</span></span><br><span class="line">	    <span class="keyword">if</span> 必须向左搜索的条件:</span><br><span class="line">		h = m</span><br><span class="line">	    <span class="keyword">else</span>:</span><br><span class="line">		l = m + <span class="number">1</span></span><br><span class="line">	<span class="keyword">return</span> l - <span class="number">1</span></span><br></pre></td></tr></table></figure></li>
<li>【非内置公式B】  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">二分查找二岔模板</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], target: <span class="built_in">int</span></span>):</span><br><span class="line">	l, h = <span class="number">0</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span></span><br><span class="line">	<span class="keyword">while</span> l &lt; h:</span><br><span class="line">	    m = (l + h) // <span class="number">2</span></span><br><span class="line">	    <span class="keyword">if</span> 满足目标或向左搜索的条件:</span><br><span class="line">		h = m</span><br><span class="line">	    <span class="keyword">else</span>:</span><br><span class="line">		l = m + <span class="number">1</span></span><br><span class="line">	<span class="keyword">return</span> l</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>☄ <strong>背景</strong></p>
<h4 id="704-二分查找"><a href="#704-二分查找" class="headerlink" title="704. 二分查找"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/binary-search/">704. 二分查找</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">search</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], target: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> l &lt;= h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> nums[m] == target:</span><br><span class="line">                <span class="keyword">return</span> m</span><br><span class="line">            <span class="keyword">elif</span> nums[m] &gt; target:</span><br><span class="line">                h = m - <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span></span><br></pre></td></tr></table></figure>
<p>☄ <strong>模板 I</strong></p>
<h4 id="69-x-的平方根"><a href="#69-x-的平方根" class="headerlink" title="69. x 的平方根"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/sqrtx/comments/">69. x 的平方根</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">mySqrt</span>(<span class="params">self, x: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        l, h = <span class="number">0</span>, x</span><br><span class="line">        <span class="keyword">while</span> l &lt; h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> m**<span class="number">2</span> &lt;= x &lt; (m+<span class="number">1</span>)**<span class="number">2</span>:</span><br><span class="line">                <span class="keyword">return</span> m</span><br><span class="line">            <span class="keyword">elif</span> m**<span class="number">2</span> &lt; x:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                h = m - <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> l</span><br></pre></td></tr></table></figure>
<h4 id="374-猜数字大小"><a href="#374-猜数字大小" class="headerlink" title="374. 猜数字大小"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/guess-number-higher-or-lower/submissions/">374. 猜数字大小</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># The guess API is already defined for you.</span></span><br><span class="line"><span class="comment"># @param num, your guess</span></span><br><span class="line"><span class="comment"># @return -1 if my number is lower, 1 if my number is higher, otherwise return 0</span></span><br><span class="line"><span class="comment"># def guess(num):</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">guessNumber</span>(<span class="params">self, n</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        :type n: int</span></span><br><span class="line"><span class="string">        :rtype: int</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        l, h = <span class="number">1</span>, n</span><br><span class="line">        <span class="keyword">while</span> l &lt;= n:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            r = guess(m)</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> r:</span><br><span class="line">                <span class="keyword">return</span> m</span><br><span class="line">            <span class="keyword">elif</span> r == <span class="number">1</span>:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                h = m - <span class="number">1</span></span><br></pre></td></tr></table></figure>
<h4 id="33-搜索旋转排序数组"><a href="#33-搜索旋转排序数组" class="headerlink" title="33. 搜索旋转排序数组"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/search-in-rotated-sorted-array/">33. 搜索旋转排序数组</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">search</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], target: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="comment"># 寻找断点</span></span><br><span class="line">        k, l, h = <span class="number">0</span>, <span class="number">1</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> l &lt;= h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> nums[m] &lt; nums[m - <span class="number">1</span>]:</span><br><span class="line">                k = m</span><br><span class="line">                <span class="keyword">break</span></span><br><span class="line">            <span class="keyword">elif</span> nums[m] &gt; nums[<span class="number">0</span>]:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                h = m - <span class="number">1</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 恢复升序</span></span><br><span class="line">        nums[k:], nums[:<span class="number">0</span>] = [], nums[k:]</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 搜索目标</span></span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> l &lt;= h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> nums[m] == target:</span><br><span class="line">                <span class="keyword">return</span> (m + k) % <span class="built_in">len</span>(nums)</span><br><span class="line">            <span class="keyword">elif</span> nums[m] &lt; target:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                h = m - <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span></span><br></pre></td></tr></table></figure>
<ul>
<li>首先通过第一个二分查找得到升序排列时的开头（也就是数组中的最小值），称其为断点 k</li>
<li>恢复数组后通过第二个二分查找得到目标索引</li>
</ul>
<p>☄ <strong>模板 II</strong></p>
<h4 id="278-第一个错误的版本"><a href="#278-第一个错误的版本" class="headerlink" title="278. 第一个错误的版本"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/first-bad-version/">278. 第一个错误的版本</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># The isBadVersion API is already defined for you.</span></span><br><span class="line"><span class="comment"># @param version, an integer</span></span><br><span class="line"><span class="comment"># @return a bool</span></span><br><span class="line"><span class="comment"># def isBadVersion(version):</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">firstBadVersion</span>(<span class="params">self, n</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        :type n: int</span></span><br><span class="line"><span class="string">        :rtype: int</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        l, h = <span class="number">1</span>, n</span><br><span class="line">        <span class="keyword">while</span> l &lt;= h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> isBadVersion(m) &gt; m * isBadVersion(m - <span class="number">1</span>):</span><br><span class="line">                <span class="keyword">return</span> m</span><br><span class="line">            <span class="keyword">elif</span> isBadVersion(m):</span><br><span class="line">                h = m - <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = m + <span class="number">1</span></span><br></pre></td></tr></table></figure>
<ul>
<li>本题二分搜索中判断返回的条件为 当前版本为True且（当前索引为0 或 左边的版本为False）</li>
<li><code>m *</code> 的作用是避免 <code>m - 1</code> 为负数，如果 m 为 0，则代表左边没有版本，只需判断当前版本是否为 True</li>
<li>True &gt; False 或 0<h4 id="162-寻找峰值"><a href="#162-寻找峰值" class="headerlink" title="162. 寻找峰值"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-peak-element/comments/">162. 寻找峰值</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findPeakElement</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> l &lt;= h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">not</span> m <span class="keyword">or</span> nums[m-<span class="number">1</span>] &lt; nums[m]) <span class="keyword">and</span> (m == <span class="built_in">len</span>(nums) - <span class="number">1</span> <span class="keyword">or</span> nums[m] &gt; nums[m+<span class="number">1</span>]):</span><br><span class="line">                <span class="keyword">return</span> m</span><br><span class="line">            <span class="keyword">elif</span> <span class="keyword">not</span> m <span class="keyword">or</span> nums[m] &gt; nums[m-<span class="number">1</span>]:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                h = m - <span class="number">1</span></span><br></pre></td></tr></table></figure></li>
<li>标准的三岔二分搜索</li>
<li>python 二分公式套路A：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findPeakElement</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        self.__class__.__getitem__ = <span class="keyword">lambda</span> self, m: m <span class="keyword">and</span> nums[m-<span class="number">1</span>] &gt; nums[m]</span><br><span class="line">        <span class="keyword">return</span> bisect.bisect_left(self, <span class="literal">True</span>, <span class="number">0</span>, <span class="built_in">len</span>(nums)) - <span class="number">1</span></span><br></pre></td></tr></table></figure>
<h4 id="153-寻找旋转排序数组中的最小值"><a href="#153-寻找旋转排序数组中的最小值" class="headerlink" title="153. 寻找旋转排序数组中的最小值"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/submissions/">153. 寻找旋转排序数组中的最小值</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findMin</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> l &lt; h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> nums[m] &lt; nums[-<span class="number">1</span>]:</span><br><span class="line">                h = m</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> nums[l]</span><br></pre></td></tr></table></figure></li>
<li>标准二岔二分搜索</li>
<li>python 二分公式套路B：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findMin</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        self.__class__.__getitem__ = <span class="keyword">lambda</span> self, m: nums[m] &lt;= nums[-<span class="number">1</span>]</span><br><span class="line">        <span class="keyword">return</span> nums[bisect.bisect_left(self, <span class="literal">True</span>, <span class="number">0</span>, <span class="built_in">len</span>(nums))]</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>☄ <strong>模板 III</strong></p>
<h4 id="34-在排序数组中查找元素的第一个和最后一个位置-1"><a href="#34-在排序数组中查找元素的第一个和最后一个位置-1" class="headerlink" title="34. 在排序数组中查找元素的第一个和最后一个位置"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/">34. 在排序数组中查找元素的第一个和最后一个位置</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">searchRange</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], target: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        r = [-<span class="number">1</span>, -<span class="number">1</span>]</span><br><span class="line">        </span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> l &lt; h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> target &lt;= nums[m]:</span><br><span class="line">                h = m</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> nums <span class="keyword">and</span> nums[l] == target:</span><br><span class="line">            r[<span class="number">0</span>] = l</span><br><span class="line">        </span><br><span class="line">        </span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> l &lt; h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> target &lt; nums[m] <span class="keyword">or</span> (target == nums[m] <span class="keyword">and</span> (m == <span class="built_in">len</span>(nums) - <span class="number">1</span> <span class="keyword">or</span> nums[m] &lt; nums[m+<span class="number">1</span>])):</span><br><span class="line">                h = m</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> nums <span class="keyword">and</span> nums[l] == target:</span><br><span class="line">            r[<span class="number">1</span>] = l</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure>
<h4 id="658-找到-K-个最接近的元素"><a href="#658-找到-K-个最接近的元素" class="headerlink" title="658. 找到 K 个最接近的元素"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-k-closest-elements/comments/">658. 找到 K 个最接近的元素</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findClosestElements</span>(<span class="params">self, arr: <span class="type">List</span>[<span class="built_in">int</span>], k: <span class="built_in">int</span>, x: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">len</span>(arr) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> l &lt; h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> arr[m] &gt;= x:</span><br><span class="line">                h = m</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">sorted</span>(<span class="built_in">sorted</span>(arr[<span class="built_in">max</span>(<span class="number">0</span>, l-k) : l+k], key=<span class="keyword">lambda</span> y: <span class="built_in">abs</span>(y - x))[:k])</span><br></pre></td></tr></table></figure>
<ul>
<li>二分查找 + 邻域排序<h4 id="162-寻找峰值-1"><a href="#162-寻找峰值-1" class="headerlink" title="162. 寻找峰值"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-peak-element/comments/">162. 寻找峰值</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findPeakElement</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> l &lt;= h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">not</span> m <span class="keyword">or</span> nums[m-<span class="number">1</span>] &lt; nums[m]) <span class="keyword">and</span> (m == <span class="built_in">len</span>(nums) - <span class="number">1</span> <span class="keyword">or</span> nums[m] &gt; nums[m+<span class="number">1</span>]):</span><br><span class="line">                <span class="keyword">return</span> m</span><br><span class="line">            <span class="keyword">elif</span> <span class="keyword">not</span> m <span class="keyword">or</span> nums[m] &gt; nums[m-<span class="number">1</span>]:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                h = m - <span class="number">1</span></span><br></pre></td></tr></table></figure></li>
<li>标准的三岔二分搜索</li>
<li>python 二分公式套路A：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findPeakElement</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        self.__class__.__getitem__ = <span class="keyword">lambda</span> self, m: m <span class="keyword">and</span> nums[m-<span class="number">1</span>] &gt; nums[m]</span><br><span class="line">        <span class="keyword">return</span> bisect.bisect_left(self, <span class="literal">True</span>, <span class="number">0</span>, <span class="built_in">len</span>(nums)) - <span class="number">1</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>☄ <strong>小结</strong></p>
<h4 id="50-Pow-x-n"><a href="#50-Pow-x-n" class="headerlink" title="50. Pow(x, n)"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/powx-n/solution/powx-n-by-leetcode/">50. Pow(x, n)</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">myPow</span>(<span class="params">self, x, n, r=<span class="number">1</span></span>) -&gt; <span class="built_in">float</span>:</span><br><span class="line">        x, n = n &lt; <span class="number">0</span> <span class="keyword">and</span> <span class="number">1</span> / x <span class="keyword">or</span> x, <span class="built_in">abs</span>(n)</span><br><span class="line">        <span class="keyword">return</span> self.myPow(x * x, n // <span class="number">2</span>, r * (<span class="keyword">not</span> n % <span class="number">2</span> <span class="keyword">or</span> x)) <span class="keyword">if</span> n <span class="keyword">else</span> r</span><br></pre></td></tr></table></figure>
<ul>
<li>尾递归 $O(\log N)$ 解法</li>
<li><code>x^4</code> 正常计算过程：<code>x * x * x * x</code>，$O(N)$</li>
<li>优化后：<code>(x**2)**2</code>，$O(\log N)$<h4 id="367-有效的完全平方数"><a href="#367-有效的完全平方数" class="headerlink" title="367. 有效的完全平方数"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/valid-perfect-square/">367. 有效的完全平方数</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isPerfectSquare</span>(<span class="params">self, num: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        l, h = <span class="number">0</span>, num</span><br><span class="line">        <span class="keyword">while</span> l &lt; h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> m * m &gt;= num:</span><br><span class="line">                h = m</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> l * l == num</span><br></pre></td></tr></table></figure></li>
<li>一个数字的算术平方根一定小于等于它自身，因此答案被限制在<code>[0, num]</code>的范围内，且待选答案呈升序排列，故可用二分查找<h4 id="744-寻找比目标字母大的最小字母"><a href="#744-寻找比目标字母大的最小字母" class="headerlink" title="744. 寻找比目标字母大的最小字母"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-smallest-letter-greater-than-target/solution/744-xun-zhao-bi-mu-biao-zi-mu-da-de-zui-xiao-zi-mu/">744. 寻找比目标字母大的最小字母</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">nextGreatestLetter</span>(<span class="params">self, letters: <span class="type">List</span>[<span class="built_in">str</span>], target: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">len</span>(letters) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> l &lt; h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> letters[m] &gt; target:</span><br><span class="line">                h = m</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> letters[l] <span class="keyword">if</span> letters[l] &gt; target <span class="keyword">else</span> letters[<span class="number">0</span>]</span><br></pre></td></tr></table></figure></li>
<li>二分查找 O(logN)</li>
<li>所谓的循环只有在数组中所有字符比目标小的时候起作用，只需要在最后增加一个判断就行了<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">nextGreatestLetter</span>(<span class="params">self, letters: <span class="type">List</span>[<span class="built_in">str</span>], target: <span class="built_in">str</span></span>) -&gt; <span class="built_in">str</span>:</span><br><span class="line">        self.__class__.__getitem__ = <span class="keyword">lambda</span> self, m: target &lt; letters[m]</span><br><span class="line">        i = bisect.bisect_left(self, <span class="literal">True</span>, <span class="number">0</span>, <span class="built_in">len</span>(letters) - <span class="number">1</span>)</span><br><span class="line">        <span class="keyword">return</span> letters[i] <span class="keyword">if</span> letters[i] &gt; target <span class="keyword">else</span> letters[<span class="number">0</span>]</span><br></pre></td></tr></table></figure></li>
<li>套路B</li>
</ul>
<p>☄ <strong>更多练习</strong></p>
<h4 id="153-寻找旋转排序数组中的最小值-1"><a href="#153-寻找旋转排序数组中的最小值-1" class="headerlink" title="153. 寻找旋转排序数组中的最小值"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/submissions/">153. 寻找旋转排序数组中的最小值</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findMin</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> l &lt; h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> nums[m] &lt; nums[-<span class="number">1</span>]:</span><br><span class="line">                h = m</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> nums[l]</span><br></pre></td></tr></table></figure>
<p>-标准二岔二分搜索</p>
<ul>
<li>python 二分公式套路B：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findMin</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        self.__class__.__getitem__ = <span class="keyword">lambda</span> self, m: nums[m] &lt;= nums[-<span class="number">1</span>]</span><br><span class="line">        <span class="keyword">return</span> nums[bisect.bisect_left(self, <span class="literal">True</span>, <span class="number">0</span>, <span class="built_in">len</span>(nums))]</span><br></pre></td></tr></table></figure>
<h4 id="154-寻找旋转排序数组中的最小值-II"><a href="#154-寻找旋转排序数组中的最小值-II" class="headerlink" title="154. 寻找旋转排序数组中的最小值 II"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii/">154. 寻找旋转排序数组中的最小值 II</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findMin</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> l &lt; h:</span><br><span class="line">            m = (l + h) // <span class="number">2</span></span><br><span class="line">            <span class="keyword">if</span> nums[m] &lt; nums[h]:</span><br><span class="line">                h = m</span><br><span class="line">            <span class="keyword">elif</span> nums[m] == nums[h]:</span><br><span class="line">                h -= <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> nums[l]</span><br></pre></td></tr></table></figure></li>
<li>每次都需要判断 m 是否在未被旋转的部分上（右部），如果在，则向左搜索，否则向右搜索</li>
<li>当 nums[m] &lt; nums[h] 时可以确定在右部，由于存在重复数字，当 m 指向的数字和 h 指向的相同时，可以直接收缩搜索范围(<code>h -= 1</code>），反正他们所代表的数字还有至少一个在搜索范围内<h4 id="349-两个数组的交集-1"><a href="#349-两个数组的交集-1" class="headerlink" title="349. 两个数组的交集"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/intersection-of-two-arrays/submissions/">349. 两个数组的交集</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">intersection</span>(<span class="params">self, nums1: <span class="type">List</span>[<span class="built_in">int</span>], nums2: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> [*<span class="built_in">set</span>(nums1) &amp; <span class="built_in">set</span>(nums2)]</span><br></pre></td></tr></table></figure></li>
<li>经过 set 之后，重复的元素被删除</li>
<li>与运算对于集合来说就是求交集<h4 id="350-两个数组的交集-II-1"><a href="#350-两个数组的交集-II-1" class="headerlink" title="350. 两个数组的交集 II"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/">350. 两个数组的交集 II</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">intersect</span>(<span class="params">self, nums1: <span class="type">List</span>[<span class="built_in">int</span>], nums2: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> [*(collections.Counter(nums1) &amp; collections.Counter(nums2)).elements()]</span><br></pre></td></tr></table></figure></li>
<li>对于两个 Counter 对象，与操作意味着取两者都有的key, value取小的那一个</li>
<li>参考：<a target="_blank" rel="noopener" href="https://www.cnblogs.com/nisen/p/6052895.html">Python Counter 计数工具</a><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">intersect</span>(<span class="params">self, nums1: <span class="type">List</span>[<span class="built_in">int</span>], nums2: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        nums1.sort()</span><br><span class="line">        nums2.sort()</span><br><span class="line">        r = []</span><br><span class="line">        i = j = <span class="number">0</span></span><br><span class="line">        <span class="keyword">while</span> i &lt; <span class="built_in">len</span>(nums1) <span class="keyword">and</span> j &lt; <span class="built_in">len</span>(nums2):</span><br><span class="line">            <span class="keyword">if</span> nums1[i] == nums2[j]:</span><br><span class="line">                r.append(nums1[i])</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">                j += <span class="number">1</span></span><br><span class="line">            <span class="keyword">elif</span> nums1[i] &lt; nums2[j]:</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                j += <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>进阶解法 ↑</li>
<li>使用双指针将两个列表中共同的元素抠下来，因为已经排序，所以遇到不同元素时数值小的那个列表的指针向前移动<h4 id="167-两数之和-II-输入有序数组-1"><a href="#167-两数之和-II-输入有序数组-1" class="headerlink" title="167. 两数之和 II - 输入有序数组"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/submissions/">167. 两数之和 II - 输入有序数组</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">twoSum</span>(<span class="params">self, numbers: <span class="type">List</span>[<span class="built_in">int</span>], target: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        i, j = <span class="number">0</span>, <span class="built_in">len</span>(numbers) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> numbers[i] + numbers[j] != target:</span><br><span class="line">            <span class="keyword">if</span> numbers[i] + numbers[j] &gt; target:</span><br><span class="line">                j -= <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> [i+<span class="number">1</span>, j+<span class="number">1</span>]</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>☄ <strong>更多练习 II</strong></p>
<h4 id="287-寻找重复数"><a href="#287-寻找重复数" class="headerlink" title="287. 寻找重复数"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-the-duplicate-number/">287. 寻找重复数</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findDuplicate</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> l &lt; h:</span><br><span class="line">            m = (l + h) &gt;&gt; <span class="number">1</span></span><br><span class="line">            <span class="keyword">if</span> <span class="built_in">sum</span>(n &lt;= m <span class="keyword">for</span> n <span class="keyword">in</span> nums) &gt; m:</span><br><span class="line">                h = m</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> l</span><br></pre></td></tr></table></figure>
<ul>
<li>本题可用二分查找，整个算法时间复杂度为 O(NlogN)，由题意可知搜索范围在 1 到 n 之间，那么如何缩小范围？只需判断数组中不超过中间数 m 的元素数量是否大于 m 即可，若大于，则表示范围 1 到 m 内肯定包含重复的数字</li>
<li>搜索范围为 [1, n]，向左（包括target）搜索的条件为：不大于 n 的数字在 nums 存在超过 m 个，即搜索范围可以被缩小为 [1, m]<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findDuplicate</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        self.__class__.__getitem__ = <span class="keyword">lambda</span> sef, m: <span class="built_in">sum</span>(n &lt;= m <span class="keyword">for</span> n <span class="keyword">in</span> nums) &gt; m</span><br><span class="line">        <span class="keyword">return</span> bisect.bisect_left(self, <span class="literal">True</span>, <span class="number">1</span>, <span class="built_in">len</span>(nums) - <span class="number">1</span>)</span><br></pre></td></tr></table></figure></li>
<li>套路B<h4 id="4-寻找两个有序数组的中位数"><a href="#4-寻找两个有序数组的中位数" class="headerlink" title="4. 寻找两个有序数组的中位数"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/median-of-two-sorted-arrays/">4. 寻找两个有序数组的中位数</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findMedianSortedArrays</span>(<span class="params">self, nums1: <span class="type">List</span>[<span class="built_in">int</span>], nums2: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">float</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">len</span>(nums1) &lt; <span class="built_in">len</span>(nums2):</span><br><span class="line">            a, b = nums1, nums2</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            a, b = nums2, nums1</span><br><span class="line">        m = (<span class="built_in">len</span>(nums1) + <span class="built_in">len</span>(nums2) - <span class="number">1</span>) &gt;&gt; <span class="number">1</span></span><br><span class="line">        </span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">len</span>(a)</span><br><span class="line">        <span class="keyword">while</span> l &lt; h:</span><br><span class="line">            i = (l + h) &gt;&gt; <span class="number">1</span></span><br><span class="line">            <span class="keyword">if</span> m-i-<span class="number">1</span> &lt; <span class="number">0</span> <span class="keyword">or</span> a[i] &gt;= b[m-i-<span class="number">1</span>]:</span><br><span class="line">                h = i</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = i + <span class="number">1</span></span><br><span class="line">        </span><br><span class="line">        r = <span class="built_in">sorted</span>(a[l: l + <span class="number">2</span>] + b[m - l: m - l + <span class="number">2</span>])</span><br><span class="line">        <span class="keyword">return</span> (r[<span class="number">0</span>] + r[<span class="number">1</span> - (<span class="built_in">len</span>(a) + <span class="built_in">len</span>(b)) % <span class="number">2</span>]) / <span class="number">2</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">findMedianSortedArrays</span>(<span class="params">self, nums1: <span class="type">List</span>[<span class="built_in">int</span>], nums2: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; <span class="built_in">float</span>:</span><br><span class="line">        a, b, m = *<span class="built_in">sorted</span>((nums1, nums2), key=<span class="built_in">len</span>), (<span class="built_in">len</span>(nums1) + <span class="built_in">len</span>(nums2) - <span class="number">1</span>) // <span class="number">2</span></span><br><span class="line">        self.__class__.__getitem__ = <span class="keyword">lambda</span> self, i: m-i-<span class="number">1</span> &lt; <span class="number">0</span> <span class="keyword">or</span> a[i] &gt;= b[m-i-<span class="number">1</span>]</span><br><span class="line">        i = bisect.bisect_left(self, <span class="literal">True</span>, <span class="number">0</span>, <span class="built_in">len</span>(a))</span><br><span class="line">        r = <span class="built_in">sorted</span>(a[i:i+<span class="number">2</span>] + b[m-i:m-i+<span class="number">2</span>])</span><br><span class="line">        <span class="keyword">return</span> (r[<span class="number">0</span>] + r[<span class="number">1</span> - (<span class="built_in">len</span>(a) + <span class="built_in">len</span>(b)) % <span class="number">2</span>]) / <span class="number">2</span></span><br></pre></td></tr></table></figure></li>
<li>本题思路与官方题解类似，时间复杂度O(log(min(m, n)))，没看过的话建议先大体了解一下</li>
<li>python 中 bisect 模块针对的是 list, 如果直接构造 list，时间复杂度为 O(min(m, n))，因此我们修改当前类的魔法方法伪造 list</li>
<li>在一个有序递增数列中，中位数左边的那部分的最大值一定小于或等于右边部分的最小值</li>
<li>如果总数组长度为奇数，m 代表中位数的索引，否则 m 代表用于计算中位数的那两个数字的左边一个。比如输入为[1,2]，[3]，那么m应该为[1,2,3]中位数2的索引1，如果输入为[1,3]，[2,4]，那么m应该为[1,2,3,4]中2的索引1</li>
<li>使用二分搜索找到 m 对应的值在a或b中对应的索引，也就是说，我们要找的中位数或中位数左部应该是 a[i] 或者 b[m-i]</li>
<li>bisect.bisect_left 搜索列表中保持列表升序的情况下，True应该插入的位置（从左侧），比如 [F,F,T] 返回 2，[F,F] 返回 2</li>
<li>这里保证 a 是 nums1 和 nums2 中较短的那个，是为了防止二分搜索的时候索引越界</li>
<li>sorted返回一个list，假设返回值是 [nums1, nums2]，那么前面加个 * 号就代表取出列表的所有内容，相当于一个迭代器，结果相当于直接写 nums1, nums2<h4 id="719-找出第-k-小的距离对"><a href="#719-找出第-k-小的距离对" class="headerlink" title="719. 找出第 k 小的距离对"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/find-k-th-smallest-pair-distance/">719. 找出第 k 小的距离对</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">smallestDistancePair</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], k: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        nums.sort()</span><br><span class="line">        </span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">max</span>(nums) - <span class="built_in">min</span>(nums)</span><br><span class="line">        <span class="keyword">while</span> l &lt; h:</span><br><span class="line">            m = (l + h) &gt;&gt; <span class="number">1</span></span><br><span class="line">            </span><br><span class="line">            <span class="comment"># 滑动窗口求小于 m 的对数</span></span><br><span class="line">            c = j = <span class="number">0</span></span><br><span class="line">            <span class="keyword">for</span> i, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(nums[:-<span class="number">1</span>]):</span><br><span class="line">                <span class="keyword">while</span> j &lt; <span class="built_in">len</span>(nums) <span class="keyword">and</span> nums[j] - nums[i] &lt;= m:</span><br><span class="line">                    j += <span class="number">1</span></span><br><span class="line">                c += j - i - <span class="number">1</span></span><br><span class="line">            </span><br><span class="line">            <span class="keyword">if</span> c &gt;= k:</span><br><span class="line">                h = m</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = m + <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> l</span><br></pre></td></tr></table></figure></li>
<li>二分搜索，总时间复杂度为 O(Nlog(max(nums) - min(nums)))</li>
<li>m 搜索范围为<code>[0, max(nums) - min(nums)]</code></li>
<li>只要满足所有数对中距离小于等于 m 的对数大于等于 k 即可向左搜索</li>
<li>判断以上条件时使用双指针滑窗，时间复杂度为 O(N)<h4 id="410-分割数组的最大值"><a href="#410-分割数组的最大值" class="headerlink" title="410. 分割数组的最大值"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/split-array-largest-sum/">410. 分割数组的最大值</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">splitArray</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], m: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        l, h = <span class="number">0</span>, <span class="built_in">sum</span>(nums)</span><br><span class="line">        <span class="keyword">while</span> l &lt; h:</span><br><span class="line">            mid = (l + h) &gt;&gt; <span class="number">1</span></span><br><span class="line">            </span><br><span class="line">            <span class="comment"># 贪心试错</span></span><br><span class="line">            c = <span class="number">1</span>; r = s = <span class="number">0</span></span><br><span class="line">            <span class="keyword">for</span> i, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(nums):</span><br><span class="line">                <span class="keyword">if</span> s + n &gt; mid:</span><br><span class="line">                    c += <span class="number">1</span></span><br><span class="line">                    r = <span class="built_in">max</span>(r, s)</span><br><span class="line">                    s = n</span><br><span class="line">                <span class="keyword">else</span>:</span><br><span class="line">                    s += n</span><br><span class="line">            r = <span class="built_in">max</span>(r, s)</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">if</span> c &lt;= m <span class="keyword">and</span> r &lt;= mid:</span><br><span class="line">                h = mid</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = mid + <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> l</span><br></pre></td></tr></table></figure></li>
<li>本题是二分搜索试错法的又一经典案例，总时间复杂度为 O(Nlog(sum(nums)))</li>
<li>我们寻求的答案（最小的子数组各自和最大值）mid 被限制于一个有序的区间 [0, sum(nums)] 之内</li>
<li>向左搜索（包括 target）的条件为：nums 可以被划分为不超过 m 个和不超过 mid 的子数组</li>
<li>判断条件成立使用了贪心算法：计数 c：nums 可以被划分为至少多少个和不超过 mid 的子数组（注意如果单个数字已经超过 mid 将被单独划分，所以最后需要判断最大子数组和 r 是否满足条件）<h3 id="🌠-二叉树"><a href="#🌠-二叉树" class="headerlink" title="🌠 二叉树"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/queue-stack/">🌠 二叉树</a></h3></li>
</ul>
<p>☄ <strong>树的遍历</strong><br><img src="tree.png" alt="tree"></p>
<h4 id="144-二叉树的前序遍历"><a href="#144-二叉树的前序遍历" class="headerlink" title="144. 二叉树的前序遍历"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/binary-tree-preorder-traversal/">144. 二叉树的前序遍历</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">preorderTraversal</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> root <span class="keyword">and</span> <span class="built_in">sum</span>(([root.val], *<span class="built_in">map</span>(self.preorderTraversal, [root.left, root.right])), []) <span class="keyword">or</span> []</span><br></pre></td></tr></table></figure>
<ul>
<li>递归遍历<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">preorderTraversal</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        r, stack = [], root <span class="keyword">and</span> [root] <span class="keyword">or</span> []</span><br><span class="line">        <span class="keyword">while</span> stack:</span><br><span class="line">            root = stack.pop()</span><br><span class="line">            r.append(root.val)</span><br><span class="line">            stack += root.right <span class="keyword">and</span> [root.right] <span class="keyword">or</span> []</span><br><span class="line">            stack += root.left <span class="keyword">and</span> [root.left] <span class="keyword">or</span> []</span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>DFS 就是前序遍历<h4 id="94-二叉树的中序遍历-1"><a href="#94-二叉树的中序遍历-1" class="headerlink" title="94. 二叉树的中序遍历"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/binary-tree-inorder-traversal/">94. 二叉树的中序遍历</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">inorderTraversal</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        r = []</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 初始化栈</span></span><br><span class="line">        stack = []</span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 进入堆栈循环</span></span><br><span class="line">        <span class="keyword">while</span> stack <span class="keyword">or</span> root:</span><br><span class="line">            <span class="keyword">if</span> root: <span class="comment"># 入栈条件</span></span><br><span class="line">                stack.append(root)</span><br><span class="line">                root = root.left</span><br><span class="line">            <span class="keyword">else</span>: <span class="comment"># 出栈条件</span></span><br><span class="line">                root = stack.pop()</span><br><span class="line">                r.append(root.val)</span><br><span class="line">                root = root.right</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>本题需使用栈来解决，关键点在于入栈条件和出栈条件的确定<h4 id="145-二叉树的后序遍历"><a href="#145-二叉树的后序遍历" class="headerlink" title="145. 二叉树的后序遍历"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/binary-tree-postorder-traversal/">145. 二叉树的后序遍历</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">postorderTraversal</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">return</span> root <span class="keyword">and</span> <span class="built_in">sum</span>((*<span class="built_in">map</span>(self.postorderTraversal, [root.left, root.right]), [root.val]), []) <span class="keyword">or</span> []</span><br></pre></td></tr></table></figure></li>
<li>递归<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">postorderTraversal</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        r, stack = [], root <span class="keyword">and</span> [root] <span class="keyword">or</span> []</span><br><span class="line">        <span class="keyword">while</span> stack:</span><br><span class="line">            root = stack.pop()</span><br><span class="line">            r.append(root.val)</span><br><span class="line">            stack += root.left <span class="keyword">and</span> [root.left] <span class="keyword">or</span> []</span><br><span class="line">            stack += root.right <span class="keyword">and</span> [root.right] <span class="keyword">or</span> []</span><br><span class="line">        <span class="keyword">return</span> r[::-<span class="number">1</span>]</span><br></pre></td></tr></table></figure></li>
<li>迭代</li>
<li>DFS的输出顺序为 <code>根-右-左</code>，我们的目标（后序遍历）为 <code>左-右-根</code>，因此只需对调整后的 DFS 逆序输出即为后序遍历<h4 id="102-二叉树的层次遍历"><a href="#102-二叉树的层次遍历" class="headerlink" title="102. 二叉树的层次遍历"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/">102. 二叉树的层次遍历</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">levelOrder</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        q = root <span class="keyword">and</span> collections.deque([(root, <span class="number">0</span>)])</span><br><span class="line">        r = []</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">while</span> q:</span><br><span class="line">            node, layer = q.popleft()</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">if</span> <span class="built_in">len</span>(r) &lt; layer + <span class="number">1</span>:</span><br><span class="line">                r.append([])</span><br><span class="line">            r[layer].append(node.val)</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">if</span> node.left:</span><br><span class="line">                q.append((node.left, layer + <span class="number">1</span>))</span><br><span class="line">            <span class="keyword">if</span> node.right:</span><br><span class="line">                q.append((node.right, layer + <span class="number">1</span>))</span><br><span class="line">            </span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>使用 BFS 遍历二叉树，队列同时记录节点与层次</li>
</ul>
<p>☄ <strong>运用递归解决树的问题</strong></p>
<ul>
<li>💡【一般思路】什么时候应该使用递归？<ul>
<li><ol>
<li>递归可以看作是四维空间中的逻辑，也就是相比普通的一个函数多了一个时间维度，当下一次的结果需要以上一次的结果作为输入时使用递归函数</li>
</ol>
</li>
<li><ol>
<li>简单来说，对于一个输入，一般的函数执行一次即可得到答案并返回，递归函数重复执行多次后返回</li>
</ol>
</li>
</ul>
</li>
<li>💡【一般思路】如何使用递归？<ul>
<li><ol>
<li>考虑初始状态</li>
</ol>
</li>
<li><ol>
<li>考虑两条支路：<ul>
<li>返回的结果还需要再次递归的结果：考虑如何连接不同时间上的俩个结果</li>
<li>返回的结果不需要再次递归的结果：通过其他条件判断后直接返回</li>
</ul>
</li>
</ol>
</li>
</ul>
</li>
<li>【套路】树形递归<ul>
<li>树形递归类题目一般将目光集中在某个节点上，考虑节点、左子节点、右子节点之间的关系，一般递归子节点</li>
<li>通常选择一个3层完美二叉树的第2层左子节点作为参考目标，然后设计递归思路<h4 id="104-二叉树的最大深度"><a href="#104-二叉树的最大深度" class="headerlink" title="104. 二叉树的最大深度"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/">104. 二叉树的最大深度</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">maxDepth</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root:</span><br><span class="line">            <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">        </span><br><span class="line">        f = self.maxDepth</span><br><span class="line">        l = f(root.left)</span><br><span class="line">        r = f(root.right)</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">max</span>(l, r) + <span class="number">1</span></span><br></pre></td></tr></table></figure>
<h4 id="101-对称二叉树"><a href="#101-对称二叉树" class="headerlink" title="101. 对称二叉树"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/symmetric-tree/">101. 对称二叉树</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isSymmetric</span>(<span class="params">self, root: TreeNode</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root <span class="keyword">or</span> root.left <span class="keyword">is</span> root.right:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">        </span><br><span class="line">        l, r = root.left, root.right</span><br><span class="line">        <span class="keyword">if</span> (l <span class="keyword">and</span> l.val) != (r <span class="keyword">and</span> r.val):</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">        </span><br><span class="line">        i, o = TreeNode(<span class="number">0</span>), TreeNode(<span class="number">0</span>)</span><br><span class="line">        i.left, i.right = l.left, r.right</span><br><span class="line">        o.left, o.right = l.right, r.left</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> self.isSymmetric(i) <span class="keyword">and</span> self.isSymmetric(o)</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li>一棵树对称意味着：<ul>
<li>左节点 == 右节点</li>
<li>左节点的左子树与右节点右子树对称</li>
<li>左节点的右子树与右节点左子树对称</li>
</ul>
</li>
<li>前6行处理特殊情况：root为None或root无子节点直接返回True，root只有一个子节点或root两个子节点不相等直接返回False</li>
<li>第一个条件在前6行处理过了，对于第二和第三个条件，我们分别构造两个假树i(inner)和o(outer)，i代表内假树，对应条件二，o代表外假树，对应条件三。递归内外假树即可<h4 id="112-路径总和"><a href="#112-路径总和" class="headerlink" title="112. 路径总和"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/path-sum/">112. 路径总和</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">hasPathSum</span>(<span class="params">self, root: TreeNode, <span class="built_in">sum</span>: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">if</span> root:</span><br><span class="line">            <span class="keyword">if</span> root.left <span class="keyword">is</span> root.right:</span><br><span class="line">                <span class="keyword">return</span> <span class="built_in">sum</span> == root.val</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l = root.left <span class="keyword">and</span> self.hasPathSum(root.left, <span class="built_in">sum</span> - root.val)</span><br><span class="line">                r = root.right <span class="keyword">and</span> self.hasPathSum(root.right, <span class="built_in">sum</span> - root.val)</span><br><span class="line">                <span class="keyword">return</span> l <span class="keyword">or</span> r</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br></pre></td></tr></table></figure></li>
<li>考虑初始状态：当树不存在时直接返回 False</li>
<li>考虑支路1：当前节点为叶节点时直接判断总和是否达到要求</li>
<li>考虑支路2：当前节点为非叶节点时将总和缩小并继续递归，判断左右节点是否存在满足条件的</li>
<li>当递归函数到达叶节点时，sum 已经被削减了多次，此时 <code>sum - node.val</code> 即为 <code>原始的sum - 整条路径的总和</code></li>
</ul>
<p>☄ <strong>总结</strong></p>
<h4 id="106-从中序与后序遍历序列构造二叉树"><a href="#106-从中序与后序遍历序列构造二叉树" class="headerlink" title="106. 从中序与后序遍历序列构造二叉树"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/comments/">106. 从中序与后序遍历序列构造二叉树</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">buildTree</span>(<span class="params">self, inorder: <span class="type">List</span>[<span class="built_in">int</span>], postorder: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; TreeNode:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> postorder:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line">        </span><br><span class="line">        root = TreeNode(postorder[-<span class="number">1</span>])</span><br><span class="line">        n = inorder.index(root.val)</span><br><span class="line">        </span><br><span class="line">        root.left = self.buildTree(inorder[:n],postorder[:n])</span><br><span class="line">        root.right = self.buildTree(inorder[n+<span class="number">1</span>:],postorder[n:-<span class="number">1</span>])</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> root</span><br></pre></td></tr></table></figure>
<ul>
<li>后序遍历顺序为 <code>左, 右, 根</code>，因此后序遍历的末尾一定为根节点</li>
<li>中序列表为 <code>[左子树中序序列, 根节点, 右子树中序序列]</code></li>
<li>后序列表为 <code>[左子树后序序列, 右子树后序序列, 根节点]</code></li>
<li>由于树中没有重复元素，我们可以通过 <code>index</code> 函数确定根节点在中序列表的位置，进而确定左右子树各自包含的节点总数，将中序与后序列表划分开</li>
<li>每次递归生成根节点并继续递归左右子节点即可<h4 id="105-从前序与中序遍历序列构造二叉树"><a href="#105-从前序与中序遍历序列构造二叉树" class="headerlink" title="105. 从前序与中序遍历序列构造二叉树"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/">105. 从前序与中序遍历序列构造二叉树</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">buildTree</span>(<span class="params">self, preorder: <span class="type">List</span>[<span class="built_in">int</span>], inorder: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; TreeNode:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> inorder:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line">        </span><br><span class="line">        root = TreeNode(preorder[<span class="number">0</span>])</span><br><span class="line">        n = inorder.index(root.val)</span><br><span class="line">        </span><br><span class="line">        root.left = self.buildTree(preorder[<span class="number">1</span>:n+<span class="number">1</span>], inorder[:n])</span><br><span class="line">        root.right = self.buildTree(preorder[n+<span class="number">1</span>:], inorder[n+<span class="number">1</span>:])</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> root</span><br></pre></td></tr></table></figure></li>
<li>前序遍历顺序为 <code>根, 左, 右</code>，因此前序遍历的开端一定为根节点</li>
<li>中序列表为 <code>[左子树中序序列, 根节点, 右子树中序序列]</code></li>
<li>前序列表为 <code>[根节点, 左子树后序序列, 右子树后序序列]</code></li>
<li>由于树中没有重复元素，我们可以通过 <code>index</code> 函数确定根节点在中序列表的位置，进而确定左右子树各自包含的节点总数，将中序与前序列表划分开</li>
<li>每次递归生成根节点并继续递归左右子节点即可<h4 id="116-填充每个节点的下一个右侧节点指针"><a href="#116-填充每个节点的下一个右侧节点指针" class="headerlink" title="116. 填充每个节点的下一个右侧节点指针"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/">116. 填充每个节点的下一个右侧节点指针</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string"># Definition for a Node.</span></span><br><span class="line"><span class="string">class Node:</span></span><br><span class="line"><span class="string">    def __init__(self, val, left, right, next):</span></span><br><span class="line"><span class="string">        self.val = val</span></span><br><span class="line"><span class="string">        self.left = left</span></span><br><span class="line"><span class="string">        self.right = right</span></span><br><span class="line"><span class="string">        self.next = next</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">connect</span>(<span class="params">self, root: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="string">&#x27;Node&#x27;</span>:</span><br><span class="line">        <span class="keyword">if</span> root <span class="keyword">and</span> root.left:</span><br><span class="line">            root.left.<span class="built_in">next</span> = root.right</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">if</span> root.<span class="built_in">next</span>:</span><br><span class="line">                root.right.<span class="built_in">next</span> = root.<span class="built_in">next</span>.left</span><br><span class="line">            </span><br><span class="line">            self.connect(root.left)</span><br><span class="line">            self.connect(root.right)</span><br><span class="line">            </span><br><span class="line">        <span class="keyword">return</span> root</span><br></pre></td></tr></table></figure></li>
<li>对于任意一次递归，只需要考虑如何设置子节点的 next 属性：<ul>
<li>将左子节点连接到右子节点</li>
<li>将右子节点连接到 <code>root.next</code> 的左子节点</li>
<li>递归左右节点<h4 id="117-填充每个节点的下一个右侧节点指针-II"><a href="#117-填充每个节点的下一个右侧节点指针-II" class="headerlink" title="117. 填充每个节点的下一个右侧节点指针 II"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/">117. 填充每个节点的下一个右侧节点指针 II</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string"># Definition for a Node.</span></span><br><span class="line"><span class="string">class Node:</span></span><br><span class="line"><span class="string">    def __init__(self, val, left, right, next):</span></span><br><span class="line"><span class="string">        self.val = val</span></span><br><span class="line"><span class="string">        self.left = left</span></span><br><span class="line"><span class="string">        self.right = right</span></span><br><span class="line"><span class="string">        self.next = next</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">connect</span>(<span class="params">self, root: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="string">&#x27;Node&#x27;</span>:</span><br><span class="line">        <span class="keyword">if</span> root <span class="keyword">and</span> (root.left <span class="keyword">or</span> root.right):</span><br><span class="line">            <span class="keyword">if</span> root.left <span class="keyword">and</span> root.right:</span><br><span class="line">                root.left.<span class="built_in">next</span> = root.right</span><br><span class="line">            </span><br><span class="line">            node = root.right <span class="keyword">or</span> root.left</span><br><span class="line">            head = root.<span class="built_in">next</span></span><br><span class="line">            <span class="keyword">while</span> head <span class="keyword">and</span> <span class="keyword">not</span> (head.left <span class="keyword">or</span> head.right):</span><br><span class="line">                head = head.<span class="built_in">next</span></span><br><span class="line">            node.<span class="built_in">next</span> = head <span class="keyword">and</span> (head.left <span class="keyword">or</span> head.right)</span><br><span class="line">            </span><br><span class="line">            self.connect(root.right)</span><br><span class="line">            self.connect(root.left)</span><br><span class="line">            </span><br><span class="line">        <span class="keyword">return</span> root</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li>对于任意一次递归，只考虑如何设置子节点的 next 属性,分为三种情况：<ul>
<li>没有子节点：直接返回</li>
<li>有一个子节点：将这个子节点的 <code>next</code> 属性设置为同层的下一个节点，即为 <code>root.next</code> 的最左边的一个节点，如果 <code>root.next</code> 没有子节点，则考虑 <code>root.next.next</code>，依次类推</li>
<li>有两个节点：左子节点指向右子节点，然后右子节点同第二种情况的做法</li>
</ul>
</li>
<li>注意递归的顺序需要从右到左<h4 id="236-二叉树的最近公共祖先"><a href="#236-二叉树的最近公共祖先" class="headerlink" title="236. 二叉树的最近公共祖先"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/">236. 二叉树的最近公共祖先</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">lowestCommonAncestor</span>(<span class="params">self, root: <span class="string">&#x27;TreeNode&#x27;</span>, p: <span class="string">&#x27;TreeNode&#x27;</span>, q: <span class="string">&#x27;TreeNode&#x27;</span></span>) -&gt; <span class="string">&#x27;TreeNode&#x27;</span>:</span><br><span class="line">        l = root.left <span class="keyword">and</span> self.lowestCommonAncestor(root.left, p, q)</span><br><span class="line">        r = root.right <span class="keyword">and</span> self.lowestCommonAncestor(root.right, p, q)</span><br><span class="line">        <span class="keyword">return</span> root <span class="keyword">if</span> root <span class="keyword">in</span> (p, q) <span class="keyword">or</span> l <span class="keyword">and</span> r <span class="keyword">else</span> l <span class="keyword">or</span> r</span><br></pre></td></tr></table></figure></li>
<li>递归全部节点，p 的祖先节点全部返回 p，q 的祖先节点全部返回 q，如果它同时是俩个节点的最近祖先，那么返回自身，否则返回 None<h4 id="297-二叉树的序列化与反序列化"><a href="#297-二叉树的序列化与反序列化" class="headerlink" title="297. 二叉树的序列化与反序列化"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/">297. 二叉树的序列化与反序列化</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode(object):</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Codec</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">serialize</span>(<span class="params">self, root</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;Encodes a tree to a single string.</span></span><br><span class="line"><span class="string">        </span></span><br><span class="line"><span class="string">        :type root: TreeNode</span></span><br><span class="line"><span class="string">        :rtype: str</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        l = []</span><br><span class="line">        q = collections.deque([root])</span><br><span class="line">        <span class="keyword">while</span> q:</span><br><span class="line">            root = q.popleft()</span><br><span class="line">            <span class="keyword">if</span> root:</span><br><span class="line">                l.append(root.val)</span><br><span class="line">                q.extend([root.left, root.right])</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                l.append(<span class="literal">None</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">str</span>(l)</span><br><span class="line">        </span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">deserialize</span>(<span class="params">self, data</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;Decodes your encoded data to tree.</span></span><br><span class="line"><span class="string">        </span></span><br><span class="line"><span class="string">        :type data: str</span></span><br><span class="line"><span class="string">        :rtype: TreeNode</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        l = <span class="built_in">eval</span>(data)</span><br><span class="line">        head = TreeNode(l[<span class="number">0</span>]) <span class="keyword">if</span> l[<span class="number">0</span>] <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span> <span class="keyword">else</span> <span class="literal">None</span></span><br><span class="line">        q = collections.deque([head])</span><br><span class="line">        i = <span class="number">1</span></span><br><span class="line">        <span class="keyword">while</span> q:</span><br><span class="line">            root = q.popleft()</span><br><span class="line">            <span class="keyword">if</span> root <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">                root.left = TreeNode(l[i]) <span class="keyword">if</span> l[i] <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span> <span class="keyword">else</span> <span class="literal">None</span></span><br><span class="line">                root.right = TreeNode(l[i + <span class="number">1</span>]) <span class="keyword">if</span> l[i + <span class="number">1</span>] <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span> <span class="keyword">else</span> <span class="literal">None</span></span><br><span class="line">                i += <span class="number">2</span></span><br><span class="line">                q.extend([root.left, root.right])</span><br><span class="line">        <span class="keyword">return</span> head</span><br><span class="line">        </span><br><span class="line"></span><br><span class="line"><span class="comment"># Your Codec object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># codec = Codec()</span></span><br><span class="line"><span class="comment"># codec.deserialize(codec.serialize(root))</span></span><br></pre></td></tr></table></figure></li>
<li>BFS扫描，记录所有节点和他们的子节点（包括 子None）</li>
<li>利用队列记录待还原节点，每次生成新节点后初始化其子节点并投入队列<h3 id="🌠-二叉搜索树"><a href="#🌠-二叉搜索树" class="headerlink" title="🌠 二叉搜索树"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/introduction-to-data-structure-binary-search-tree/">🌠 二叉搜索树</a></h3></li>
</ul>
<p>☄ <strong>二叉搜索树简介</strong></p>
<h4 id="98-验证二叉搜索树"><a href="#98-验证二叉搜索树" class="headerlink" title="98. 验证二叉搜索树"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/validate-binary-search-tree/">98. 验证二叉搜索树</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isValidBST</span>(<span class="params">self, root: TreeNode, first=<span class="literal">True</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root:</span><br><span class="line">            <span class="keyword">return</span> first <span class="keyword">or</span> []</span><br><span class="line">        </span><br><span class="line">        f = self.isValidBST</span><br><span class="line">        l = f(root.left, <span class="number">0</span>) + [root.val] + f(root.right, <span class="number">0</span>)</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">all</span>([a &gt; b <span class="keyword">for</span> a, b <span class="keyword">in</span> <span class="built_in">zip</span>(l[<span class="number">1</span>:], l)]) <span class="keyword">if</span> first <span class="keyword">else</span> l</span><br></pre></td></tr></table></figure>
<ul>
<li>搜索二叉树的中序遍历结果呈升序</li>
<li>若当前递归节点为根（<code>first</code> 为 <code>True</code>）则判断遍历结果是否呈升序，否则返回中序遍历列表用于拼接<h4 id="173-二叉搜索树迭代器"><a href="#173-二叉搜索树迭代器" class="headerlink" title="173. 二叉搜索树迭代器"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/binary-search-tree-iterator/">173. 二叉搜索树迭代器</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">BSTIterator</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, root: TreeNode</span>):</span><br><span class="line">        self.s = []</span><br><span class="line">        <span class="keyword">while</span> root:</span><br><span class="line">            self.s.append(root)</span><br><span class="line">            root = root.left</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">next</span>(<span class="params">self</span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        @return the next smallest number</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        r = self.s.pop()</span><br><span class="line">        root = r.right</span><br><span class="line">        <span class="keyword">while</span> root:</span><br><span class="line">            self.s.append(root)</span><br><span class="line">            root = root.left</span><br><span class="line">        <span class="keyword">return</span> r.val</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">hasNext</span>(<span class="params">self</span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        @return whether we have a next smallest number</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">bool</span>(self.s)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your BSTIterator object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = BSTIterator(root)</span></span><br><span class="line"><span class="comment"># param_1 = obj.next()</span></span><br><span class="line"><span class="comment"># param_2 = obj.hasNext()</span></span><br></pre></td></tr></table></figure></li>
<li>模拟中序遍历的迭代过程，使用堆栈 <code>self.s</code> 进行深度优先搜索</li>
<li>空间复杂度为 O(树的高度)</li>
<li>平均时间复杂度 = 循环总次数（N） / 迭代器长度（N） = O(1)</li>
</ul>
<p>☄ <strong>在二叉搜索树中实现搜索操作</strong></p>
<h4 id="700-二叉搜索树中的搜索"><a href="#700-二叉搜索树中的搜索" class="headerlink" title="700. 二叉搜索树中的搜索"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/search-in-a-binary-search-tree/">700. 二叉搜索树中的搜索</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">searchBST</span>(<span class="params">self, root: TreeNode, val: <span class="built_in">int</span></span>) -&gt; TreeNode:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root <span class="keyword">or</span> root.val == val:</span><br><span class="line">            <span class="keyword">return</span> root</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            root = root.right <span class="keyword">if</span> root.val &lt; val <span class="keyword">else</span> root.left</span><br><span class="line">            <span class="keyword">return</span> self.searchBST(root, val)</span><br></pre></td></tr></table></figure>
<ul>
<li>根据BST的特性，对于每个节点：<ul>
<li>如果目标值等于节点的值，则返回节点;</li>
<li>如果目标值小于节点的值，则继续在左子树中搜索;</li>
<li>如果目标值大于节点的值，则继续在右子树中搜索。<h4 id="701-二叉搜索树中的插入操作"><a href="#701-二叉搜索树中的插入操作" class="headerlink" title="701. 二叉搜索树中的插入操作"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/">701. 二叉搜索树中的插入操作</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">insertIntoBST</span>(<span class="params">self, root: TreeNode, val: <span class="built_in">int</span></span>) -&gt; TreeNode:</span><br><span class="line">        root = copy.deepcopy(root)</span><br><span class="line">        stack = [root]</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">while</span> stack:</span><br><span class="line">            node = stack.pop()</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">if</span> node.val &gt; val:</span><br><span class="line">                <span class="keyword">if</span> node.left:</span><br><span class="line">                    stack.append(node.left)</span><br><span class="line">                <span class="keyword">else</span>:</span><br><span class="line">                    node.left = TreeNode(val)</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">if</span> node.right:</span><br><span class="line">                    stack.append(node.right)</span><br><span class="line">                <span class="keyword">else</span>:</span><br><span class="line">                    node.right = TreeNode(val)</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> root</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li>此处遵循经典插入方法，种使整体操作变化最小</li>
<li>寻找到合适的叶位置后插入新节点，这样的操作只需要在原树的某个叶节点处延伸一个节点</li>
<li>这里可以直接深拷贝构造新树，然后修改<h4 id="450-删除二叉搜索树中的节点"><a href="#450-删除二叉搜索树中的节点" class="headerlink" title="450. 删除二叉搜索树中的节点"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/delete-node-in-a-bst/">450. 删除二叉搜索树中的节点</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">deleteNode</span>(<span class="params">self, root: TreeNode, key: <span class="built_in">int</span></span>) -&gt; TreeNode:</span><br><span class="line">        dummy = TreeNode(<span class="built_in">float</span>(<span class="string">&#x27;-inf&#x27;</span>))</span><br><span class="line">        dummy.right = root</span><br><span class="line">        root = dummy</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">while</span> root:</span><br><span class="line">            child_str = <span class="string">&#x27;root.left&#x27;</span> <span class="keyword">if</span> root.val &gt; key <span class="keyword">else</span> <span class="string">&#x27;root.right&#x27;</span></span><br><span class="line">            child = <span class="built_in">eval</span>(child_str)</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> child <span class="keyword">or</span> child.val != key: <span class="comment"># 继续搜索删除目标的父节点</span></span><br><span class="line">                root = child</span><br><span class="line">            <span class="keyword">else</span>: <span class="comment"># 已经找到删除目标的父节点 root 和目标 child</span></span><br><span class="line">                <span class="keyword">if</span> child.left <span class="keyword">is</span> child.right: <span class="comment"># 情况1.目标没有子节点</span></span><br><span class="line">                    <span class="built_in">exec</span>(<span class="string">f&#x27;<span class="subst">&#123;child_str&#125;</span> = None&#x27;</span>)</span><br><span class="line">                <span class="keyword">elif</span> <span class="keyword">not</span> (child.left <span class="keyword">and</span> child.right): <span class="comment"># 情况2.目标只有左子或右子</span></span><br><span class="line">                    <span class="built_in">exec</span>(<span class="string">f&#x27;<span class="subst">&#123;child_str&#125;</span> = child.left or child.right&#x27;</span>)</span><br><span class="line">                <span class="keyword">else</span>: <span class="comment"># 情况3.目标有左子和右子</span></span><br><span class="line">                    parent = child</span><br><span class="line">                    root = parent.right</span><br><span class="line">                    </span><br><span class="line">                    <span class="keyword">while</span> root <span class="keyword">and</span> root.left: <span class="comment"># 搜索中序后继节点</span></span><br><span class="line">                        parent, root = root, root.left</span><br><span class="line">                        </span><br><span class="line">                    child.val = root.val</span><br><span class="line">                    side = <span class="string">&#x27;right&#x27;</span> <span class="keyword">if</span> parent <span class="keyword">is</span> child <span class="keyword">else</span> <span class="string">&#x27;left&#x27;</span></span><br><span class="line">                    <span class="built_in">exec</span>(<span class="string">f&#x27;parent.<span class="subst">&#123;side&#125;</span> = root.right&#x27;</span>)</span><br><span class="line">                    </span><br><span class="line">        <span class="keyword">return</span> dummy.right</span><br></pre></td></tr></table></figure></li>
<li>此类题目细节比较多，建议罗列所有情况后再写代码</li>
<li>本段代码为迭代流，涉及复杂知识点 <a target="_blank" rel="noopener" href="https://www.cnblogs.com/yangmingxianshen/p/7810496.html">eval, exec</a>, <a target="_blank" rel="noopener" href="https://www.jianshu.com/p/651a68f1fea9">中序后继节点</a>，主要思想同<a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/introduction-to-data-structure-binary-search-tree/65/basic-operations-in-a-bst/179/">探索介绍的</a>，尽量保持原树结构</li>
<li>首先可以分为俩类情况，删除目标为 root 或不为 root，构建一个虚拟节点连接上原来的 root，即可把所有情况归为删除目标不为 root 类</li>
<li>细分有3种情况：<ul>
<li>目标没有子节点：直接删除</li>
<li>目标只有左子或右子：用目标唯一的子节点替换目标</li>
<li>目标有左子和右子：替换目标的值为中序后继节点的值并删除后继节点</li>
</ul>
</li>
</ul>
<p>☄ <strong>小结</strong></p>
<h4 id="703-数据流中的第K大元素"><a href="#703-数据流中的第K大元素" class="headerlink" title="703. 数据流中的第K大元素"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/kth-largest-element-in-a-stream/">703. 数据流中的第K大元素</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">KthLargest</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, k: <span class="built_in">int</span>, nums</span>):</span><br><span class="line">        self.k, self.nums = k, heapq.nlargest(k, nums + [<span class="built_in">float</span>(<span class="string">&#x27;-inf&#x27;</span>)])</span><br><span class="line">        heapq.heapify(self.nums)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">add</span>(<span class="params">self, val: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        heapq.heappushpop(self.nums,val)</span><br><span class="line">        <span class="keyword">return</span> self.nums[<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Your KthLargest object will be instantiated and called as such:</span></span><br><span class="line"><span class="comment"># obj = KthLargest(k, nums)</span></span><br><span class="line"><span class="comment"># param_1 = obj.add(val)</span></span><br></pre></td></tr></table></figure>
<ul>
<li>题目中提到 len(nums) &gt;= k-1，因此我们加入一个无穷小使得 len(nums) &gt;= k，以便构造一个 k 尺寸的小根堆</li>
<li>堆中的数据意味着从第 k 大的数字到最大的数字</li>
<li>维护堆的时间复杂度为 O(Tlogk)<h4 id="236-二叉树的最近公共祖先-1"><a href="#236-二叉树的最近公共祖先-1" class="headerlink" title="236. 二叉树的最近公共祖先"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/">236. 二叉树的最近公共祖先</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">lowestCommonAncestor</span>(<span class="params">self, root: <span class="string">&#x27;TreeNode&#x27;</span>, p: <span class="string">&#x27;TreeNode&#x27;</span>, q: <span class="string">&#x27;TreeNode&#x27;</span></span>) -&gt; <span class="string">&#x27;TreeNode&#x27;</span>:</span><br><span class="line">        l = root.left <span class="keyword">and</span> self.lowestCommonAncestor(root.left, p, q)</span><br><span class="line">        r = root.right <span class="keyword">and</span> self.lowestCommonAncestor(root.right, p, q)</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> root <span class="keyword">in</span> (p, q) <span class="keyword">or</span> l <span class="keyword">and</span> r:</span><br><span class="line">            <span class="keyword">return</span> root</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> l <span class="keyword">or</span> r</span><br></pre></td></tr></table></figure></li>
<li>递归全部节点，p 的祖先节点返回 p，q 的祖先节点返回 q，否则返回 None</li>
<li>如果同时是俩个节点的最近祖先，也就是 p，q 分别位于左右子树，或者本身是 p、q 中的一个，那么返回自身<h4 id="220-存在重复元素-III"><a href="#220-存在重复元素-III" class="headerlink" title="220. 存在重复元素 III"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/contains-duplicate-iii/">220. 存在重复元素 III</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">containsNearbyAlmostDuplicate</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>], k: <span class="built_in">int</span>, t: <span class="built_in">int</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        l = []</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">for</span> j, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(nums):</span><br><span class="line">            <span class="keyword">if</span> j &gt; k: <span class="comment"># 滑动窗口</span></span><br><span class="line">                <span class="keyword">del</span> l[bisect.bisect_left(l, nums[j - k - <span class="number">1</span>], <span class="number">0</span>, <span class="built_in">len</span>(l))]</span><br><span class="line">            </span><br><span class="line">            i = bisect.bisect_left(l, n, <span class="number">0</span>, <span class="built_in">len</span>(l))</span><br><span class="line">            l.insert(i, n)</span><br><span class="line">            <span class="keyword">if</span> i <span class="keyword">and</span> <span class="built_in">abs</span>(l[i] - l[i - <span class="number">1</span>]) &lt;= t <span class="keyword">or</span> i &lt; <span class="built_in">len</span>(l) - <span class="number">1</span> <span class="keyword">and</span> <span class="built_in">abs</span>(l[i] - l[i + <span class="number">1</span>]) &lt;= t:</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> <span class="literal">False</span></span><br></pre></td></tr></table></figure></li>
<li>k 实际上限制了滑动窗口的大小，对于每个数字，我们只需要检查其前面的 k-1 个数字中是否存在与当前数字距离不超过 t 的数字即可</li>
<li>检查的方法是在升序的列表中检查当前数字所在索引的左右两侧是否波动不超过 t</li>
<li>因为使用了窗口，所以维护排序只需在之前已经排好序的数组 l 的基础上保持升序得插入新数字即可，这里使用二分查找搜索插入位置</li>
<li>时间复杂度为 O(Nlog(min(N, K))) 空间复杂度为 O(min(N, K))</li>
</ul>
<p>☄ <strong>附录：高度平衡的二叉搜索树</strong></p>
<h4 id="110-平衡二叉树"><a href="#110-平衡二叉树" class="headerlink" title="110. 平衡二叉树"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/balanced-binary-tree/">110. 平衡二叉树</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">isBalanced</span>(<span class="params">self, root: TreeNode, first=<span class="literal">True</span></span>) -&gt; <span class="built_in">bool</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">True</span> <span class="keyword">if</span> first <span class="keyword">else</span> <span class="number">0</span></span><br><span class="line">        </span><br><span class="line">        l = self.isBalanced(root.left, <span class="literal">False</span>)</span><br><span class="line">        r = self.isBalanced(root.right, <span class="literal">False</span>)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> l <span class="keyword">is</span> <span class="literal">False</span> <span class="keyword">or</span> r <span class="keyword">is</span> <span class="literal">False</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">abs</span>(l - r) &lt;= <span class="number">1</span> <span class="keyword">and</span> <span class="built_in">max</span>(l, r) + <span class="number">1</span></span><br></pre></td></tr></table></figure>
<ul>
<li>DFS递归每个节点</li>
<li>如果这个节点不平衡，那么这棵树肯定不平衡，它和它的所有父节点都返回 False</li>
<li>如果节点平衡，则返回当前树的高度 + 1（如果是根节点，直接返回True）<h4 id="108-将有序数组转换为二叉搜索树"><a href="#108-将有序数组转换为二叉搜索树" class="headerlink" title="108. 将有序数组转换为二叉搜索树"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/">108. 将有序数组转换为二叉搜索树</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">sortedArrayToBST</span>(<span class="params">self, nums: <span class="type">List</span>[<span class="built_in">int</span>]</span>) -&gt; TreeNode:</span><br><span class="line">        <span class="keyword">if</span> nums:</span><br><span class="line">            m = <span class="built_in">len</span>(nums) // <span class="number">2</span></span><br><span class="line">            r = TreeNode(nums[m])</span><br><span class="line">            r.left, r.right = <span class="built_in">map</span>(self.sortedArrayToBST, [nums[:m], nums[m+<span class="number">1</span>:]])</span><br><span class="line">            <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>平衡二叉搜索树需要保证俩点：<ul>
<li>根节点大于左子树任意节点，小于右子树任意节点</li>
<li>左右子数高度相差不超过 1</li>
</ul>
</li>
<li>由以上性质，一个可行的递归条件可以得出：<ul>
<li>每次返回的根节点处于数组中间，以其左右半数组分别递归构造左右子树</li>
<li>那么就意味着左子小于根，右子大于根，且所有节点左右子树节点数相差不超过 1 （由于递归的构树方式相同，所有节点都满足高度平衡）</li>
</ul>
</li>
</ul>
<h3 id="🌠-N叉树"><a href="#🌠-N叉树" class="headerlink" title="🌠 N叉树"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/n-ary-tree/">🌠 N叉树</a></h3><p>☄ <strong>遍历</strong></p>
<h4 id="589-N叉树的前序遍历"><a href="#589-N叉树的前序遍历" class="headerlink" title="589. N叉树的前序遍历"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/">589. N叉树的前序遍历</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string"># Definition for a Node.</span></span><br><span class="line"><span class="string">class Node:</span></span><br><span class="line"><span class="string">    def __init__(self, val=None, children):</span></span><br><span class="line"><span class="string">        self.val = val</span></span><br><span class="line"><span class="string">        self.children = children</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">preorder</span>(<span class="params">self, root: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        s = <span class="built_in">bool</span>(root) * [root]</span><br><span class="line">        r = []</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">while</span> s:</span><br><span class="line">            root = s.pop()</span><br><span class="line">            r.append(root.val)</span><br><span class="line">            s += root.children[::-<span class="number">1</span>]</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure>
<ul>
<li>root 为 <code>[]</code> 时 bool 值为 <code>False</code> 同 <code>0</code>，乘法结果为 <code>[]</code>，即可跳过 <code>while</code></li>
<li>root 非空时 dfs 栈式迭代</li>
<li>逆转 <code>children</code> 是由于栈的 <code>FILO(先入后出)</code> 特性<h4 id="590-N-ary-Tree-Postorder-Traversal"><a href="#590-N-ary-Tree-Postorder-Traversal" class="headerlink" title="590. N-ary Tree Postorder Traversal"></a><a target="_blank" rel="noopener" href="https://leetcode.com/problems/n-ary-tree-postorder-traversal/">590. N-ary Tree Postorder Traversal</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string"># Definition for a Node.</span></span><br><span class="line"><span class="string">class Node:</span></span><br><span class="line"><span class="string">    def __init__(self, val=None, children=None):</span></span><br><span class="line"><span class="string">        self.val = val</span></span><br><span class="line"><span class="string">        self.children = children</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">postorder</span>(<span class="params">self, root: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        s = <span class="built_in">bool</span>(root) * [root]</span><br><span class="line">        r = []</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">while</span> s:</span><br><span class="line">            root = s.pop()</span><br><span class="line">            r.append(root.val)</span><br><span class="line">            s += root.children</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> r[::-<span class="number">1</span>]</span><br></pre></td></tr></table></figure></li>
<li>后序遍历为 <code>左右根</code>，只需将前序遍历 <code>根左右</code> 的子节点遍历顺序逆转并倒序输出即可，大体做法同前一题<h4 id="429-N叉树的层序遍历"><a href="#429-N叉树的层序遍历" class="headerlink" title="429. N叉树的层序遍历"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/">429. N叉树的层序遍历</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string"># Definition for a Node.</span></span><br><span class="line"><span class="string">class Node:</span></span><br><span class="line"><span class="string">    def __init__(self, val, children):</span></span><br><span class="line"><span class="string">        self.val = val</span></span><br><span class="line"><span class="string">        self.children = children</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">levelOrder</span>(<span class="params">self, root: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        q = root <span class="keyword">and</span> collections.deque([(root, <span class="number">0</span>)])</span><br><span class="line">        r = []</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">while</span> q:</span><br><span class="line">            root, layer = q.pop()</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">if</span> <span class="built_in">len</span>(r) &lt; layer + <span class="number">1</span>:</span><br><span class="line">                r.append([])</span><br><span class="line">            </span><br><span class="line">            r[layer].append((root.val))</span><br><span class="line">            q.extendleft([(child, layer + <span class="number">1</span>) <span class="keyword">for</span> child <span class="keyword">in</span> root.children])</span><br><span class="line">            </span><br><span class="line">        <span class="keyword">return</span> r</span><br></pre></td></tr></table></figure></li>
<li>使用队列 BFS 遍历</li>
<li>在队列中多保留一个层次序号记录相应层索引</li>
</ul>
<p>☄ <strong>递归</strong></p>
<h4 id="559-N叉树的最大深度"><a href="#559-N叉树的最大深度" class="headerlink" title="559. N叉树的最大深度"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/">559. N叉树的最大深度</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string"># Definition for a Node.</span></span><br><span class="line"><span class="string">class Node:</span></span><br><span class="line"><span class="string">    def __init__(self, val=None, children=None):</span></span><br><span class="line"><span class="string">        self.val = val</span></span><br><span class="line"><span class="string">        self.children = children</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">maxDepth</span>(<span class="params">self, root: <span class="string">&#x27;Node&#x27;</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> root <span class="keyword">and</span> <span class="number">1</span> + <span class="built_in">max</span>(<span class="built_in">map</span>(self.maxDepth, root.children <span class="keyword">or</span> [<span class="literal">None</span>])) <span class="keyword">or</span> <span class="number">0</span></span><br></pre></td></tr></table></figure>
<ul>
<li>Bottom Up 递归</li>
</ul>
<h2 id="精选"><a href="#精选" class="headerlink" title="精选"></a>精选</h2><h3 id="🌠-递归-I"><a href="#🌠-递归-I" class="headerlink" title="🌠 递归 I"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/explore/learn/card/queue-stack/">🌠 递归 I</a></h3><p>☄ <strong>递归原理</strong></p>
<h4 id="344-反转字符串-1"><a href="#344-反转字符串-1" class="headerlink" title="344. 反转字符串"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/reverse-string/">344. 反转字符串</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">reverseString</span>(<span class="params">self, s: <span class="type">List</span>[<span class="built_in">str</span>]</span>) -&gt; <span class="literal">None</span>:</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        Do not return anything, modify s in-place instead.</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(s) - <span class="number">1</span>, <span class="number">0</span>, -<span class="number">1</span>):</span><br><span class="line">            s.insert(i, s.pop(<span class="number">0</span>))</span><br></pre></td></tr></table></figure>
<ul>
<li>取出来，插到对应位置<h4 id="24-两两交换链表中的节点"><a href="#24-两两交换链表中的节点" class="headerlink" title="24. 两两交换链表中的节点"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/swap-nodes-in-pairs/">24. 两两交换链表中的节点</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">swapPairs</span>(<span class="params">self, head: ListNode</span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">if</span> head <span class="keyword">and</span> head.<span class="built_in">next</span>:</span><br><span class="line">            seco = head.<span class="built_in">next</span></span><br><span class="line">            head.<span class="built_in">next</span> = self.swapPairs(seco.<span class="built_in">next</span>)</span><br><span class="line">            seco.<span class="built_in">next</span> = head</span><br><span class="line">            <span class="keyword">return</span> seco</span><br><span class="line">        <span class="keyword">return</span> head</span><br></pre></td></tr></table></figure></li>
<li>交换列表中的前两个节点，也就是 <code>head</code> 和 <code>head.next(seco)</code></li>
<li><code>seco</code> 指向 <code>head</code>，<code>head</code> 指向递归 <code>seco.next</code> 后返回的后序链表的头结点</li>
<li>返回新的头结点 <code>seco</code></li>
</ul>
<p>☄ <strong>递推关系</strong></p>
<h4 id="118-杨辉三角-1"><a href="#118-杨辉三角-1" class="headerlink" title="118. 杨辉三角"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/pascals-triangle/">118. 杨辉三角</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">generate</span>(<span class="params">self, numRows: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="type">List</span>[<span class="built_in">int</span>]]:</span><br><span class="line">        <span class="keyword">if</span> numRows &lt;= <span class="number">1</span>:</span><br><span class="line">            <span class="keyword">return</span> numRows * [[<span class="number">1</span>]]</span><br><span class="line">        </span><br><span class="line">        prev = self.generate(numRows - <span class="number">1</span>)</span><br><span class="line">        last = [<span class="built_in">sum</span>(prev[-<span class="number">1</span>][j-<span class="number">1</span>:j+<span class="number">1</span>]) <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, numRows-<span class="number">1</span>)]</span><br><span class="line">        prev.append([<span class="number">1</span>, *last, <span class="number">1</span>])</span><br><span class="line">        <span class="keyword">return</span> prev</span><br></pre></td></tr></table></figure>
<ul>
<li>首先判断特殊情况，<code>numRows</code> 为 0 则返回 <code>[]</code>，为 1 返回 <code>[[1]]</code></li>
<li>通过递归获得前几层结果 <code>prev</code></li>
<li>通过上一层结果计算新的最后一层结果 <code>last</code>，<code>f(i,j) = f(i−1, j−1) + f(i−1, j)</code> （两边的 1 会在下一行代码中另外加）</li>
<li>加入新行并返回<h4 id="119-杨辉三角-II-1"><a href="#119-杨辉三角-II-1" class="headerlink" title="119. 杨辉三角 II"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/pascals-triangle-ii/">119. 杨辉三角 II</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">getRow</span>(<span class="params">self, rowIndex: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[<span class="built_in">int</span>]:</span><br><span class="line">        <span class="keyword">if</span> rowIndex == <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">return</span> [<span class="number">1</span>]</span><br><span class="line">        </span><br><span class="line">        prev = self.getRow(rowIndex - <span class="number">1</span>)</span><br><span class="line">        last = [<span class="built_in">sum</span>(prev[j-<span class="number">1</span>:j+<span class="number">1</span>]) <span class="keyword">for</span> j <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, rowIndex)]</span><br><span class="line">        <span class="keyword">return</span> [<span class="number">1</span>, *last, <span class="number">1</span>]</span><br></pre></td></tr></table></figure></li>
<li>和前一题基本一致<h4 id="206-反转链表-1"><a href="#206-反转链表-1" class="headerlink" title="206. 反转链表"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/reverse-linked-list/">206. 反转链表</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">reverseList</span>(<span class="params">self, head: ListNode, tail=<span class="literal">None</span></span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">if</span> head:</span><br><span class="line">            head.<span class="built_in">next</span>, tail, head = tail, head, head.<span class="built_in">next</span></span><br><span class="line">            <span class="keyword">return</span> self.reverseList(head, tail)</span><br><span class="line">        <span class="keyword">return</span> tail</span><br></pre></td></tr></table></figure></li>
<li>对于每一次递归，将当前节点的 <code>next</code> 属性指向前一个节点，然后递归调用下一个节点</li>
<li>如果当前节点为 <code>None</code> 则返回上一个节点，否则返回递归一下个节点的结果</li>
</ul>
<p>☄ <strong>Memoization（记忆化）技术</strong></p>
<ul>
<li><code>递归 + 记忆</code> = <code>动态规划</code><h4 id="509-斐波那契数"><a href="#509-斐波那契数" class="headerlink" title="509. 斐波那契数"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/fibonacci-number/">509. 斐波那契数</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    cache = &#123;<span class="number">0</span>:<span class="number">0</span>, <span class="number">1</span>:<span class="number">1</span>&#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">fib</span>(<span class="params">self, N: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">if</span> N <span class="keyword">not</span> <span class="keyword">in</span> self.cache:</span><br><span class="line">            self.cache[N] = <span class="built_in">sum</span>(<span class="built_in">map</span>(self.fib, [N - <span class="number">1</span>, N - <span class="number">2</span>]))</span><br><span class="line">            </span><br><span class="line">        <span class="keyword">return</span> self.cache[N]</span><br></pre></td></tr></table></figure></li>
<li>使用哈希记忆进行剪枝<h4 id="70-爬楼梯"><a href="#70-爬楼梯" class="headerlink" title="70. 爬楼梯"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/climbing-stairs/">70. 爬楼梯</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    d = &#123;<span class="number">0</span>:<span class="number">0</span>, <span class="number">1</span>:<span class="number">1</span>, <span class="number">2</span>:<span class="number">2</span>&#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">climbStairs</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">if</span> n <span class="keyword">not</span> <span class="keyword">in</span> self.d:</span><br><span class="line">            self.d[n] = <span class="built_in">sum</span>(<span class="built_in">map</span>(self.climbStairs, [n - <span class="number">1</span>, n - <span class="number">2</span>]))</span><br><span class="line">            </span><br><span class="line">        <span class="keyword">return</span> self.d[n]</span><br></pre></td></tr></table></figure></li>
<li>到这一层的方法数 = 到前二层方法数的总和</li>
</ul>
<p>☄ <strong>复杂度分析</strong></p>
<h4 id="104-二叉树的最大深度-1"><a href="#104-二叉树的最大深度-1" class="headerlink" title="104. 二叉树的最大深度"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/">104. 二叉树的最大深度</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="comment"># class TreeNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.left = None</span></span><br><span class="line"><span class="comment">#         self.right = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">maxDepth</span>(<span class="params">self, root: TreeNode, prev=<span class="number">0</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> root:</span><br><span class="line">            <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">        </span><br><span class="line">        f = self.maxDepth</span><br><span class="line">        l = f(root.left)</span><br><span class="line">        r = f(root.right)</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">max</span>(l, r) + <span class="number">1</span></span><br></pre></td></tr></table></figure>
<ul>
<li>时间复杂度：O(N)，每次递归访问一个节点，总共N个节点</li>
<li>空间复杂度：O(N)，最糟糕的情况是树完全不平衡，递归开栈消耗 O(N) 空间<h4 id="50-Pow-x-n-1"><a href="#50-Pow-x-n-1" class="headerlink" title="50. Pow(x, n)"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/powx-n/">50. Pow(x, n)</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">myPow</span>(<span class="params">self, x: <span class="built_in">float</span>, n: <span class="built_in">int</span></span>) -&gt; <span class="built_in">float</span>:</span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">abs</span>(n) &lt;= <span class="number">1</span>:</span><br><span class="line">            <span class="keyword">return</span> (<span class="number">1</span>, x, <span class="number">1</span>/x)[n]</span><br><span class="line">        </span><br><span class="line">        root = self.myPow(x, n // <span class="number">2</span>)</span><br><span class="line">        <span class="keyword">return</span> (<span class="number">1</span>, x)[n % <span class="number">2</span>] * root * root</span><br></pre></td></tr></table></figure></li>
<li>时间复杂度：$O(\log N)$</li>
<li>空间复杂度：$O(\log N)$</li>
<li>$x^4 = x^2 * x^2$， $x^5 = x^2 * x^2 * x$， 借此方法可以缩减计算量</li>
</ul>
<p>☄ <strong>总结</strong></p>
<h4 id="21-合并两个有序链表-1"><a href="#21-合并两个有序链表-1" class="headerlink" title="21. 合并两个有序链表"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/merge-two-sorted-lists/">21. 合并两个有序链表</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for singly-linked list.</span></span><br><span class="line"><span class="comment"># class ListNode:</span></span><br><span class="line"><span class="comment">#     def __init__(self, x):</span></span><br><span class="line"><span class="comment">#         self.val = x</span></span><br><span class="line"><span class="comment">#         self.next = None</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">mergeTwoLists</span>(<span class="params">self, l1: ListNode, l2: ListNode</span>) -&gt; ListNode:</span><br><span class="line">        <span class="keyword">if</span> l1 <span class="keyword">and</span> l2:</span><br><span class="line">            <span class="keyword">if</span> l1.val &gt; l2.val: l1, l2 = l2, l1</span><br><span class="line">            l1.<span class="built_in">next</span> = self.mergeTwoLists(l1.<span class="built_in">next</span>, l2)</span><br><span class="line">        <span class="keyword">return</span> l1 <span class="keyword">or</span> l2</span><br></pre></td></tr></table></figure>
<h4 id="779-第K个语法符号"><a href="#779-第K个语法符号" class="headerlink" title="779. 第K个语法符号"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/k-th-symbol-in-grammar/comments/">779. 第K个语法符号</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">kthGrammar</span>(<span class="params">self, N: <span class="built_in">int</span>, K: <span class="built_in">int</span></span>) -&gt; <span class="built_in">int</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span> <span class="keyword">if</span> N == <span class="number">1</span> <span class="keyword">else</span> (K + <span class="number">1</span>) % <span class="number">2</span> ^ self.kthGrammar(N - <span class="number">1</span>, (K + <span class="number">1</span>) // <span class="number">2</span>);</span><br></pre></td></tr></table></figure>
<ul>
<li>由于递推关系式可知第 <code>N</code> 行的第 <code>K</code> 个数计算自第 <code>N - 1</code> 行的第 <code>(K + 1) // 2</code> 个数</li>
<li>我们称第 <code>N</code> 行的第 <code>K</code> 个数为C，第 <code>N - 1</code> 行的第 <code>(K + 1) // 2</code> 个数为 P</li>
<li><code>0 → 01</code>，<code>1 → 10</code>，可见变换后实际上是在原来的数字后加了相对的数（这里称 0 与 1 相对），那么如果 K 为奇数则 <code>C = P</code>，否则 <code>C = P 的相对数</code><h4 id="95-不同的二叉搜索树-II"><a href="#95-不同的二叉搜索树-II" class="headerlink" title="95. 不同的二叉搜索树 II"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/unique-binary-search-trees-ii/">95. 不同的二叉搜索树 II</a></h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Definition for a binary tree node.</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">TreeNode</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, x, l=<span class="literal">None</span>, r=<span class="literal">None</span></span>):</span><br><span class="line">        self.val = x</span><br><span class="line">        self.left = l</span><br><span class="line">        self.right = r</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Solution</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">generateTrees</span>(<span class="params">self, n: <span class="built_in">int</span></span>) -&gt; <span class="type">List</span>[TreeNode]:</span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">gen</span>(<span class="params">num</span>):</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> num: <span class="keyword">yield</span> <span class="literal">None</span></span><br><span class="line">            <span class="keyword">for</span> i, n <span class="keyword">in</span> <span class="built_in">enumerate</span>(num):</span><br><span class="line">                <span class="keyword">for</span> l <span class="keyword">in</span> gen(num[:i]):</span><br><span class="line">                    <span class="keyword">for</span> r <span class="keyword">in</span> gen(num[i + <span class="number">1</span>:]):</span><br><span class="line">                        <span class="keyword">yield</span> TreeNode(n, l, r)</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">bool</span>(n) * [*gen([*<span class="built_in">range</span>(<span class="number">1</span>, <span class="number">1</span> + n)])]</span><br></pre></td></tr></table></figure></li>
<li>构建递归生成器 <code>gen</code>，输入是一系列升序的数字，返回这些数字可能构成的所有二叉树结构</li>
<li>首先，所有数字都有可能作为根，因此遍历 <code>num</code> 作为根</li>
<li>根据二叉搜索树的特性（左子树所有节点小于根，右子树大于），可知根的左子树由比根小的数字构成，递归 <code>num[:i]</code> 就是左子树所有的可能结构，同理可获得右子树所有可能的结构</li>
<li>左右递归结果的笛卡尔积 + <code>root</code>，即为整棵树所有可能的结构</li>
</ul>
<h1 id="常用技巧总结"><a href="#常用技巧总结" class="headerlink" title="常用技巧总结"></a>常用技巧总结</h1><ul>
<li>set 中的 in 操作时间复杂度为 O(1)</li>
<li>dict.get 可以设置预设值，避免取到不存在的 key 时报错</li>
<li>遇到关于数组的问题，不妨先想想是否应该先排序</li>
<li>最短路径搜索问题通常使用 bfs</li>
<li>迭代器是缩小 space efficiency 的利器</li>
<li>让数字在一定范围内循环递增常常使用 % 操作</li>
<li>a &lt;&lt; b 相当于 <code>a * 2**b</code>，a &gt;&gt; b 相当于 <code>a // 2**b</code></li>
<li>a, b = a + b, a - b 的计算顺序为：<ul>
<li>a + b</li>
<li>a - b</li>
<li>赋值 a</li>
<li>赋值 b</li>
</ul>
</li>
<li>a = b = 1 + 1 的计算顺序为：<ul>
<li>1 + 1</li>
<li>赋值 a</li>
<li>赋值 b</li>
</ul>
</li>
</ul>
<h1 id="隐藏的坑"><a href="#隐藏的坑" class="headerlink" title="隐藏的坑"></a>隐藏的坑</h1><ul>
<li>遍历 set 时，输出是无序的，输出顺序可能随着计算机环境而改变</li>
<li><code>[True, False, 0].index(0)</code> 输出为 1，因为 False == 0 为真，但 False is 0 为假</li>
<li><code>/</code> 为浮点数除法，<code>//</code> 为整数除法。<code>eg. 8 / 2.5 = 3.2, 8 // 2.5 = 3.0</code>，注意 <code>//</code> 的结果不一定为整数型，<code>a//b</code> 的结果值等价于 <code>math.floor(a / b)</code></li>
<li>使用记忆化技术时，字典在多个 case 之间共享，应该考虑不同 case 的 key 是否相互影响</li>
</ul>
<h1 id="解法汇总贡献者"><a href="#解法汇总贡献者" class="headerlink" title="解法汇总贡献者"></a>解法汇总贡献者</h1><p>注：此处贡献名单仅代表汇总搜集贡献，不代表全部原创，欢迎所有更短的解法🤓</p>
<ul>
<li>此处排名不分先后，仅以首次参与时间记录，感谢所有贡献者🤟</li>
<li><a target="_blank" rel="noopener" href="https://github.com/cy69855522">Knife丶</a>[QQ1272068154  微信ly18597591102]</li>
<li><a target="_blank" rel="noopener" href="https://github.com/zdylzdyl">zdylzdyl</a></li>
<li><a target="_blank" rel="noopener" href="https://github.com/ajinwu">ajin</a></li>
<li><a target="_blank" rel="noopener" href="https://github.com/grg909">grg909</a></li>
<li><a target="_blank" rel="noopener" href="https://github.com/Lebhoryi">Lebhoryi</a></li>
</ul>

      
    </div>
    <div class="article-footer">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-license">
      <strong>文章作者： </strong><a href="https://hwame.top" style="color:#E541E5;"> 鴻塵</a>
    </li>
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://hwame.top/20200604/shortest-leetcode-python-solutions.html" title="力扣简洁优雅的python解法" target="_blank" rel="external" style="color:#E541E5;">https://hwame.top/20200604/shortest-leetcode-python-solutions.html</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用《<a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external" style="color:#E541E5;"><u>CC BY 4.0 CN协议</u></a>》许可协议。转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://hwame.top" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://hwame.top" target="_blank"><span class="text-dark">鴻塵</span><small class="ml-1x">Pythoner, Data Analyst</small></a></h3>
        <div>个人简介：处女座不适合做码农。</div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	
      <div id="vcomments"></div>
    
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/20201008/render-matplotlib-figure-to-flaskweb.html" title="如何将matplotlib图像渲染到前端"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a>
    </li>
    
    
    <li class="next">
      <a href="/20200527/retry-from-try-clause-when-catch-error-in-python.html" title="Python捕获异常后如何对try语句重试"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
    <li class="toggle-toc">
      <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false" title="文章目录" role="button">
        <span style="color:#C71585">[&nbsp;</span><span style="color:#C71585">文章目录</span>
        <i class="text-collapsed icon icon-anchor"></i>
        <i class="text-in icon icon-close"></i>
        <span style="color:#C71585">]</span>
      </a>
    </li>
    
  </ul>
  
  
  
  <div class="bar-right">
    
    <div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter" data-mobile-sites="weibo,wechat,qq,qzone"></div>
    
  </div>
  </div>
</nav>
  


</main>

  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/hwame" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="https://weibo.com/hwamei" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="https://www.zhihu.com/people/hwame" target="_blank" title="Zhihu" data-toggle=tooltip data-placement=top><i class="icon icon-zhihu"></i></a></li>
        
        <li><a href="https://segmentfault.com/u/hwame" target="_blank" title="Segmentfault" data-toggle=tooltip data-placement=top><i class="icon icon-segmentfault"></i></a></li>
        
        <li><a href="https://gitee.com/hwame" target="_blank" title="Gitee" data-toggle=tooltip data-placement=top><i class="icon icon-gitee"></i></a></li>
        
        <li><a href="/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        &copy; 2025 鴻塵
        
        
        <div class="publishby" style="font-family:Courier">
            <span id="busuanzi_container_site_pv">
                <i class="icon icon-eye"></i><span id="busuanzi_value_site_pv" style="font-family:Courier"></span>&nbsp;
                <i class="icon icon-users"></i><span id="busuanzi_value_site_uv" style="font-family:Courier"></span>
            </span>
            <!--
            <br>✯<a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/" style="color:#0FFFAA">鄂ICP备2020019329号</a>
            -->
            <br><i class="icon icon-clock" style="transform:rotate(90deg)"></i><span id="sitetime" style="font-family:Courier"></span>
        </div>
        
        <!--
        <div class="publishby">
        	Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.
        </div>
        -->
    </div>
    
</footer>
<script>
    function siteTime(){
        window.setTimeout("siteTime()", 1000);
        var seconds = 1000;
        var minutes = seconds * 60;
        var hours = minutes * 60;
        var days = hours * 24;
        var years = days * 365;
        var today = new Date();
        var todayYear = today.getFullYear();
        var todayMonth = today.getMonth()+1;
        var todayDate = today.getDate();
        var todayHour = today.getHours();
        var todayMinute = today.getMinutes();
        var todaySecond = today.getSeconds();
        /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
        year - 作为date对象的年份，为4位年份值
        month - 0-11之间的整数，做为date对象的月份
        day - 1-31之间的整数，做为date对象的天数
        hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
        minutes - 0-59之间的整数，做为date对象的分钟数
        seconds - 0-59之间的整数，做为date对象的秒数
        microseconds - 0-999之间的整数，做为date对象的毫秒数 */
        var t1 = Date.UTC(2020,05,19,21,20,52); //建站时间
        var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
        var diff = t2-t1;
        var diffYears = Math.floor(diff/years);
        var diffDays = Math.floor((diff/days)-diffYears*365);
        var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
        var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
        var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
        // 将「数字」转「补零字符串」
        var y = diffYears.toString()
        var d = diffDays.toString().padStart(3, '0')
        var h = diffHours.toString().padStart(2, '0')
        var m = diffMinutes.toString().padStart(2, '0')
        var s = diffSeconds.toString().padStart(2, '0')
        document.getElementById("sitetime").innerHTML=y+":"+d+":"+h+":"+m+":"+s;
    }
    siteTime();
</script>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<div id="go-top"></div>
<style type="text/css">
#go-top {
 width:40px;height:40px;
 background-color:#DDA0DD;
 position:relative;
 border-radius:20px;
 position:fixed;right:20px;bottom:50px;
 cursor:pointer;display:none;
}
#go-top:after {
 content:" ";
 position:absolute;left:14px;top:14px;
 border-top:2px solid #fff;border-right:2px solid #fff;
 width:12px;height:12px;
 transform:rotate(-45deg);
}
#go-top:hover {
 background-color:#8A2BE2;
}
</style>
<script>
$(function () {
  var top=$("#go-top");
  $(window).scroll(function () {
    ($(window).scrollTop() > 300) ? top.show(300) : top.hide(200);
    $("#go-top").click(function () {
      $('body,html').animate({scrollTop:0});
      return false();
    })
  });
});
</script>

<script src="/js/plugin.min.js"></script>


<script src="/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/js/insight.js"></script>





   




   
    

  <script src='/waline.js'></script>
  <link rel="stylesheet" type="text/css" href="/waline.css" />
  
  <script type="text/javascript">
 
  
Waline.init({
      el: '#vcomments',
      serverURL: 'https://waline.hwame.top',
});
  </script>

     


<!-- 20201211添加判断 -->

   
  <script src="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script>
  <script>
  //利用 FancyBox 实现点击图片放大
  $(document).ready(function() {
    $('article img').not('[hidden]').not('.panel-body img').each(function() {
      var $image = $(this);
      var imageCaption = $image.attr('alt');
      var $imageWrapLink = $image.parent('a');
      if ($imageWrapLink.length < 1) {
        var src = this.getAttribute('src');
        var idx = src.lastIndexOf('?');
        if (idx != -1) {
          src = src.substring(0, idx);
        }
        $imageWrapLink = $image.wrap('<a href="' + src + '"></a>').parent('a');
      }
      $imageWrapLink.attr('data-fancybox', 'images');
      if (imageCaption) {
        $imageWrapLink.attr('data-caption', imageCaption);
      }
    });
    $().fancybox({
      selector: '[data-fancybox="images"]',
      hash: false,
      loop: true,
    });
  });
  </script>







  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
      z-index: 2;
    }

    .highlight-wrap:hover .copy-btn,
        .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  
  <script>
    addLoadEvent(()=>{
      $('.highlight').each(function (i, e) {
        var $wrap = $('<div>').addClass('highlight-wrap')
        $(e).after($wrap)
        $wrap.append($('<button>').addClass('copy-btn').append('一键复制').on('click', function (e) {
          var code = $(this).parent().find(".code")[0].innerText
          
          var ta = document.createElement('textarea')
          document.body.appendChild(ta)
          ta.style.position = 'absolute'
          ta.style.top = '0px'
          ta.style.left = '0px'
          ta.value = code
          ta.select()
          ta.focus()
          var result = document.execCommand('copy')
          document.body.removeChild(ta)
          
            if(result)$(this).text('复制成功')
            else $(this).text('复制失败')
          
          $(this).blur()
        })).on('mouseleave', function (e) {
          var $b = $(this).find('.copy-btn')
          setTimeout(function () {
            $b.text('一键复制')
          }, 300)
        }).append(e)
      })
    })
  </script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html>